Multiplication of three numbers in c give a wrong results?

情到浓时终转凉″ 提交于 2019-11-28 14:21:59

问题


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

double den = 180*3600*10000 ;

in debugging a got this value -2109934592.0000000

any help please ???

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 ;
}

回答1:


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

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

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



回答2:


test.c: In function ‘main’:
test.c:6:37: warning: integer overflow in expression [-Woverflow]
      double denominator =  10000*180*3600 ;
                                     ^

Is the error when I compile. Your overflowing ints and casting to a double.

   double denominator =  10000.0*180.0*3600.0 ;

Fixes the issue



来源:https://stackoverflow.com/questions/26428107/multiplication-of-three-numbers-in-c-give-a-wrong-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!