Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

c - Int overflow with floating point values

Just getting started in C programming and learning about overflow. The following code I created has no issues and complies fine. What I want to know is why? For instance when I replace variables product1 and avg1 with the datatype long long why would it result in an output of nan nan. Why would using type double be better than long long when the size in terms of bytes are similar? Also was it valid for me to cast type double when variables are double already.

#include <stdio.h>

int main(void) {
   int userNum1;
   int userNum2;
   int userNum3;
   int userNum4;
   
   /* Type your code here. */
   scanf("%d %d %d %d", &userNum1, &userNum2, &userNum3, &userNum4);
   
   int product = userNum1 * userNum2 * userNum3 * userNum4;
   double product1 = (double)userNum1 * userNum2 * userNum3 * userNum4;
   int avg = (userNum1 + userNum2 + userNum3 + userNum4) / 4;
   double  avg1 = ((double)userNum1 + userNum2 + userNum3 + userNum4) / 4; 
   printf("%d %d
", product, avg);
   printf("%0.3lf %0.3lf
", product1, avg1);  

   return 0;
}

desired output when input is 8 10 5 4

1600 6 //output of ints
1600.000 6.750 //floating points
question from:https://stackoverflow.com/questions/65851389/int-overflow-with-floating-point-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What I want to know is why?

Code compiled but not with a well enabled compiler.

Save time, enable all warnings - it is more productive than posting on SO.

long long  product1 = userNum1 * userNum2 * userNum3 * userNum4;
...
printf("%0.3lf %0.3lf
", product1, avg1);

warning: format '%lf' expects argument of type 'double', but argument 2 has type 'long long int' [-Wformat=]

Use matching print specifiers like "%g" with double and "%lld" with long long.


Also was it valid for me to cast type double when variables are double already.

Yes, but unnecessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...