将c中的三个数字相乘会得出错误的结果? [英] Multiplication of three numbers in c give a wrong results?

查看:86
本文介绍了将c中的三个数字相乘会得出错误的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法相信程序中发生的事情

I can't belive what's happen in my program

double den = 180*3600*10000 ;

在调试中得到了这个值-2109934592.0000000

in debugging a got this value -2109934592.0000000

有什么帮助吗?

您可以尝试以下简单代码

you can try this simple code

#include<stdio.h>
#include<math.h>

int main ( int argc , char *argv )
{
double denominator =  10000*180*3600 ;

printf("%f \n", denominator ) ;
return 0 ;
}

推荐答案

有了问题中的完整代码,我们现在可以看到这是整数溢出.

With the full code in the question we can now see it's an integer overflow.

10000 * 180 * 3600 = 6,480,000,000.

此值大于2,147,483,648,这是32位有符号整数的最大值.乘法结果溢出到-2,109,934,592,然后转换为两倍.

This is greater than 2,147,483,648 which is the max value of a 32-bit signed int. The results of the multiplication overflows to -2,109,934,592 and is then converted to double.

要获得正确的结果,请在进行乘法运算之前将数字之一加倍:

To get the right result make one of the numbers a double before you do the multiplication:

10000.0 * 180 * 3600

这篇关于将c中的三个数字相乘会得出错误的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆