c - 如果我们从 2^63 中减去 1000,为什么结果会少 1024 而不是 1000?
问题描述
你能解释为什么差异是 1024 而不是 1000 吗?
int main(void) {
unsigned long long int x = pow(2,63);
double y = pow(2,63) - 1000;
double z = 9223372036854775808.0 - 1000.0;
printf("%llu\n%f\n%f\n", x,y,z);
}
输出是:
9223372036854775808
9223372036854774784.000000
9223372036854774784.000000
解决方案
因为在 type 可表示的浮点数中double
,9223372036854774784
恰好最接近数学上正确的结果9223372036854774808
。
让我们检查一下你的有代表性的社区9223372036854774784
#include <float.h>
#include <math.h>
#include <stdio.h>
int main()
{
double d = 9223372036854774784;
printf("%lf\n%lf\n%lf\n", nextafter(d, -DBL_MAX), d, nextafter(d, DBL_MAX));
}
在我的平台上,输出是
9223372036854773760.000000
9223372036854774784.000000
9223372036854775808.000000
你会选择哪一个?您的实施决定使用9223372036854774784
.