C 程序如何显示最大可能的 unsigned long long 的值?

How can a C program show the value of the largest possible unsigned long long?

下面的程序不应该打印出 2^64 -1 的整数值吗?

#include <stdio.h>
#include <math.h>

int main(void) 
{
    printf ("%llu\n" , ( unsigned long long int ) ( pow (2 ,  8 * sizeof (unsigned long long) ) - 1 ) ) ;

    return 0;
}

函数pow returns a double,通常为64位浮点型,尾数为53位。这不足以解析 264 附近的数字,粒度为 1.

下一个小于 264 的可表示 double 值是 264 − 2048 = 2 64 − 211。 264 − 1 仍然是 264,这是最接近的可表示值。将其转换为 unsigned long long,您将得到 0.

如果您需要最大可能的值 unsigned long long,您可以使用 ULLONG_MAX from <limits.h>:

printf ("%llu\n", ULLONG_MAX);    // need <limits.h>

(unsigned long long) 0 的补码 – 一个设置了所有位的 unsigned long long – 也应该有效:

printf ("%llu\n", ~0ull);