Strange unsigned long long int behavior

天涯浪子 提交于 2019-12-24 16:44:17

问题


I was using unsigned long long int for some calculations but

std::cout << std::setprecision(30) << 900000000000001i64+4*pow(10, 16);

Gives Output:40900000000000000

and this

std::cout << std::setprecision(30) << 900000000000011i64+4*pow(10, 16);

Gives Output:40900000000000008

Now i have no idea what is happening i tried removing i64 tries printing 4*pow(10, 16) gives the correct result 40000000000000000 also tried printing 40900000000000011 directly, it prints the correct result. It works fine for power of 10^14 but after that it starts to behave strangely.

Can someone explain what is happening?


回答1:


The reason you get this awkward result is because of loosing the values of the least significant bits in double type. double mantissa can only hold about 15 decimal digits and exactly 52 binary digits (wiki).

900000000000001i64+4*pow(10, 16) will be converted to double trimming all lower bits. In you case there are 3 of them.

Example:

std::cout << std::setprecision(30);
std::cout << 900000000000001i64 + 4 * pow(10, 16) << endl;
std::cout << 900000000000002i64 + 4 * pow(10, 16) << endl;
std::cout << 900000000000003i64 + 4 * pow(10, 16) << endl;
std::cout << 900000000000004i64 + 4 * pow(10, 16) << endl;
std::cout << 900000000000005i64 + 4 * pow(10, 16) << endl;
std::cout << 900000000000006i64 + 4 * pow(10, 16) << endl;
std::cout << 900000000000007i64 + 4 * pow(10, 16) << endl;
std::cout << 900000000000008i64 + 4 * pow(10, 16) << endl;
std::cout << 900000000000009i64 + 4 * pow(10, 16) << endl;

will produce result:

40900000000000000
40900000000000000
40900000000000000
40900000000000000
40900000000000008
40900000000000008
40900000000000008
40900000000000008
40900000000000008
40090000000000008

Notice how the values are rounded to 23.




回答2:


Please try this code (notice the explicit type conversion there).

typedef unsigned long long ULONG64; //Not a must, but just for code clarity

std::cout << std::setprecision(30) << 900000000000001i64 + (ULONG64)(4 * pow(10, 16));
//output -> 40900000000000001
std::cout << std::setprecision(30) << 900000000000011i64 + (ULONG64)(4 * pow(10, 16));
//output -> 40900000000000011

You have to tell compiler to do explicit type conversion (to ULONG64) on result returned by pow(...) function which is of type double.



来源:https://stackoverflow.com/questions/35968967/strange-unsigned-long-long-int-behavior

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