如何在C ++中保持Double的精度 [英] How to maintain Double's precision in C++

查看:411
本文介绍了如何在C ++中保持Double的精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  main()
{
double d1 = 1234.1;
cout<< d1 = 1234.1 - ><< d1< ENDL;
double d2 = 1234.099999;
cout<< d2 = 1234.099999 - ><< d2< ENDL;



$ b $ p $输出:

  d1 = 1234.1  - > 1234.1 
d2 = 1234.099999 - > 1234.1

实际上我想打印 d2 ,也就是 1234.099999 ,但是没有一样。



请建议如何得到确切的值。

解决方案

您想 cout.precision

b
$ b

另外请注意,d2不是1234.099999,而d1不是1234.1

浮点数引入舍入误差,这就是为什么默认情况下,它们会绕到更少的位置,以尝试显示有意义的结果。


main()
{
   double d1 = 1234.1;
   cout << "d1 = 1234.1 --> " << d1 << endl;
   double d2 = 1234.099999;
   cout << "d2 = 1234.099999 --> " << d2 << endl;
}

Output:

d1 = 1234.1 --> 1234.1
d2 = 1234.099999 --> 1234.1

I actually want to print the exact value of d2, i.e. 1234.099999 but not getting the same.

Please suggest how can I get the exact value.

解决方案

You want cout.precision http://www.cplusplus.com/reference/iostream/ios_base/precision/

Also note that d2 is not quite 1234.099999, and d1 is not quite 1234.1

Floating point numbers introduce rounding errors, which is why they round to fewer places by default, to try to display a meaningful result.

这篇关于如何在C ++中保持Double的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆