c - 如何解决 c 中的 int 溢出问题

标签 c

在 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 type unsigned long.
  • If preceding condition not met, and if either operand is of type long and the other of type unsigned int, both operands are converted to type unsigned long.
  • If the preceding two conditions are not met, and if either operand is of type long, the other operand is converted to type long.
  • If the preceding three conditions are not met, and if either operand is of type unsigned int, the other operand is converted to type unsigned 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;

现场观看:http://ideone.com/pA2Pvm

关于c - 如何解决 c 中的 int 溢出问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22285377/

相关文章:

c - 为什么在以下代码中将成员 y 设置为 0?

c - 需要使用 c 为错误处理提供超时

c - 为什么 ruby​​ scanf 这么慢?

c - 数字图像处理

c++ - 实现插件支持的最佳方式

c - scanf: "%[^\n]"跳过第二个输入但 "%[^\n]"没有。为什么?

c++ - 在 Qt 中使用完成信号退出线程并进行 clean_up 的正确方法

c - 访问通过引用接收的结构体的成员

c - 查找 argv[] 中的重复字符

c - Lex(词法分析器)中正则表达式的大问题