我试图通过gcc编译器执行此代码:
#include <stdio.h>
int main()
{
unsigned long long int x;
x = 75000 * 75000;
printf ("%llu\n", x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但它给出了错误的输出.
然后我尝试了这个:
#include <stdio.h>
int main()
{
unsigned long long int x;
x = (unsigned long long)75000 * (unsigned long long)75000;
printf ("%llu\n", x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它给出了正确的输出!
为什么会这样?
表达式75000 * 75000是两个整数常量的乘法.该表达式的结果也是一个整数,可以溢出.然后将结果分配给unsigned long long,但它已经溢出,因此结果是错误的.
要编写无符号长long常量,请使用ULL后缀.
x = 75000ULL * 75000ULL;
Run Code Online (Sandbox Code Playgroud)
现在乘法不会溢出.
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |