【发布时间】:2021-07-23 09:39:47
【问题描述】:
int orders=1000000000;
int mod=pow(10,9)+7;
unsigned int total=4294967295;
total=(orders*(orders+1))%mod;
total/=2;
return total;
预期答案= 21
但是得到
运行时错误:有符号整数溢出:1000000000 * 1000000001 不能用“int”类型表示
我也试过
int orders=1000000000;
int mod=pow(10,9)+7;
long long total=0LL;
total=(long long)(orders*(orders+1))%mod;
total/=2;
return total;
同样的错误
//使用最新的C++ 17标准使用clang 11编译。
我可以知道为什么会这样吗? 我想也许 long long 被截断为 int 因此为 0LL, 但这仍然没有解决问题。
在其他编译器上尝试时, 获取输出
对于第一个代码:
-243309312
第二段代码:
1904174336
【问题讨论】:
-
不要在调查整数行为的程序中使用
pow;因为在查看您的问题之前,我们首先必须排除浮点问题。为什么不直接输入整数常量来替换pow(10,9)? -
orders是一个int。(orders*(orders+1))%mod都是ints -
(orders*(orders+1))%mod;中没有无符号整数,所以计算是有符号的。赋值运算符的 LHS 上的结果类型不参与 RHS 上表达式的类型转换,直到表达式被计算并且结果即将被赋值。注意(a * b) mod m == ((a mod m) * (b mod m)) mod m -
您尝试将两个有符号的 32 位整数相乘,每个整数都是 10⁹。
-
你需要学习模运算来解决它而不会溢出。
标签: c++ c++11 integer-overflow