为什么用 std::cin 读取一个巨大的双精度值时,值会略有变化?
我发现std::cin的一个奇怪的行为(在Win 10下使用VS 17):当输入大量数字时,std::cin正在读取的数字接近但不同。 有没有对大数进行近似的方法? 如何获得与输入的数字完全相同的数字?
double n(0);
cout << "Enter a number > 0 (0 to exit): ";
cin.clear(); // does not help !
cin >> n; // enter 2361235441021745907775
printf("Selected number %.0f \n", n); // 2361235441021746151424 is processed ?.
输出
Enter a number > 0 (0 to exit):
2361235441021745907775
Selected number 2361235441021746151424
I found a strange behavior of std::cin (using VS 17 under Win 10): when a large number is entered, the number that std::cin is reading is close but different.
Is there any kind of approximation done with large numbers ?
How to get the exact same large number than entered ?
double n(0);
cout << "Enter a number > 0 (0 to exit): ";
cin.clear(); // does not help !
cin >> n; // enter 2361235441021745907775
printf("Selected number %.0f \n", n); // 2361235441021746151424 is processed ?.
Output
Enter a number > 0 (0 to exit):
2361235441021745907775
Selected number 2361235441021746151424
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要了解有效位数。双精度型可以容纳非常大的值,但它只能处理这么多的数字。搜索
C++ doubles effectivedigits
并阅读 400 个讨论该问题的网页。如果您需要更多的数字,则需要使用 double 以外的数字。如果您知道它是整数,而不是浮点数,则可以使用
long long int
,它至少有8个字节并且可以容纳2^63-1
。如果您知道它是正数,则可以将其设置为unsigned long long int
,并且您将获得 0 到至少 18,446,744,073,709,551,615 (2^64-1
) 的范围。如果您需要更多数字,则需要找到支持任意长整数的库。谷歌
c++任意精度整数
会给你一些指导。You need to learn about number of significant digits. A double can hold very large values, but it will only handle so many digits. Do a search for
C++ doubles significant digits
and read any of the 400 web pages that talk about it.If you need more digits than that, you need to use something other than double. If you know it's an integer, not floating point, you can use
long long int
which is at least 8 bytes and can hold2^63-1
. If you know it's a positive number, you can make itunsigned long long int
and you get the range 0 to at least 18,446,744,073,709,551,615 (2^64-1
).If you need even more digits, you need to find a library that supports arbitrarily long integers. A google for
c++ arbitrary precision integer
will give you some guidance.