在编写C++代码时,我突然意识到我的数字被错误地转换double为unsigned long long.
具体来说,我使用以下代码:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <limits>
using namespace std;
int main()
{
unsigned long long ull = numeric_limits<unsigned long long>::max();
double d = static_cast<double>(ull);
unsigned long long ull2 = static_cast<unsigned long long>(d);
cout << ull << endl << d << endl << ull2 << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我的计算机上执行此代码时,我有以下输出:
18446744073709551615
1.84467e+019
9223372036854775808
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)
我期望第一个和第三个数字完全相同(就像在Ideone上一样),因为我确信它long double占用了10个字节,并将尾数存储在其中的8个中.我会理解,如果第三个数字与第一个数字相比被截断 - 只是因为浮点数格式的错误.但这里的价值是两倍不同!
所以,主要的问题是:为什么?我怎样才能预测出这种情况呢?
一些细节:我在Windows 7上使用Visual Studio …