在 C 语言中,是否可以在不导致整数溢出的情况下执行以下操作? 我的答案需要是一个整数,我稍后会在程序中使用它。代码打印-337。 正确答案应该是 2014 年。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int i;
i = (10000 * 735625 + 14780)/3652425;
printf("%d",i);
return 0;
}
最佳答案
基于usual arithmetic conversions ,当 10000 * 735625 + 14780
(超出 int
的范围)尝试保存到 int
时,它将溢出。
Integral promotions are performed on the operands as follows:
- If either operand is of type
unsigned long
, the other operand is converted to typeunsigned long
.- If preceding condition not met, and if either operand is of type
long
and the other of typeunsigned int
, both operands are converted to typeunsigned long
.- If the preceding two conditions are not met, and if either operand is of type
long
, the other operand is converted to typelong
.- If the preceding three conditions are not met, and if either operand is of type
unsigned int
, the other operand is converted to typeunsigned int
.- If none of the preceding conditions are met, both operands are converted to type
int
.
要计算,您需要使用long long
(范围更大)。
正如 @JoachimIsaksson 所建议的,一种简单的方法是将 LL
放在 10000
之后,以 long long
的精度进行计算:
i = ( 10000LL * 735625 + 14780)/3652425;
关于c - 如何解决 c 中的 int 溢出问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22285377/