You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么这段C语言代码计算50000×60000时结果错误?

问题原因:有符号整数溢出

先计算乘积:50000 * 60000 = 3000000000。

C语言中,int类型通常是32位有符号整数,它的取值范围是 -2147483648 到 2147483647(即 -2^31 至 2^31-1)。30亿明显超出了这个范围,触发了有符号整数溢出。

虽然C标准将有符号整数溢出定义为未定义行为,但多数主流编译器(如GCC、Clang)会按补码循环溢出处理:当数值超出上限时,会从类型的最小值开始循环计数。30亿截断为32位补码后,结果就是 -1294967296,也就是你看到的异常输出。

而小于50000和60000的数字组合,乘积未超过int的最大值,所以能得到正确结果。

解决方法

  • 使用更大范围的整数类型,比如long long:
    #include <stdio.h>
    int main() 
    {
      long long a = 50000;
      long long b = 60000;
      long long c = a * b;
      printf("The product of a and b is %lld", c);
      return 0;
    }
    
  • 或在计算时强制转换类型,避免溢出:
    #include <stdio.h>
    int main() 
    {
      int a = 50000;
      int b = 60000;
      long long c = (long long)a * b;
      printf("The product of a and b is %lld", c);
      return 0;
    }
    

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 17:01:05