How to maintain Double's precision in C++

巧了我就是萌 提交于 2020-01-14 03:15:29

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/5191018/how-to-maintain-doubles-precision-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!