c - 整数乘积溢出

标签 c overflow

在下面的代码中,prod 的值不是 9,000,000;它得到一个垃圾值。为什么我们需要 num1 和 num2 是 long 类型?

#include <stdio.h>
int main()
{
    int num1 = 3000, num2 = 3000;
    long int prod = num1 * num2;
    printf("%ld\n", prod);
    return 0;
}

最佳答案

当 num1*num2 被计算时,它被存储在一个相同类型(即 int)的中间变量中,由于它不够大而成为垃圾。然后,中间变量存储在一个long int中,但是计算出的答案已经变成了垃圾。

解决方案是转换乘法的参数之一。

long int prod = (long int)num1 * num2;

这样,中间计算将使用两个类型中较大的一个,并将其临时存储为一个 long int。

关于c - 整数乘积溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3764727/

相关文章:

css - 在 IE 6 中使容器溢出其父级而不使父级变大?

CSS 属性溢出 :hidden causes inner divs to appear below main div

c++ - 特殊情况: Is & faster than %?

压缩多行 C 函数原型(prototype)

c - 为什么当 strcpy() 导致缓冲区溢出时没有段错误?

c# - 内存溢出 : Having an increasing number of Microsoft. CSharp.RuntimeBinder.Semantics

html - 当溢出设置为滚动时,使 child 扩展到 parent 的宽度

C 中字符串的比较

c - LibBSON 导出到缓冲区

在不知道语言的情况下大小写 UTF-8