开发者

How to maintain Double's precision in C++

开发者 https://www.devze.com 2023-02-15 05:51 出处:网络
main() { double d1 = 1234.1; cout << \"d1 = 1234.1 --> \" << d1 << endl; double d2 = 1234.099999;
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 get开发者_高级运维ting 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号