DEZMO27
DEZMO27

Reputation: 37

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\n", product, avg);
   printf("%0.3lf %0.3lf\n", product1, avg1);  

   return 0;
}

desired output when input is 8 10 5 4

1600 6 //output of ints
1600.000 6.750 //floating points

Upvotes: 1

Views: 115

Answers (2)

Rohan Bari
Rohan Bari

Reputation: 7726

What I want to know is why?

You would get the least number of error messages by default because of not setting advanced flags. You should consider adding -pedantic and -Wall flags to increase the warning level.

... why would it result in an output of nan nan?

It's not necessary everyone will get output like that, in my case, it was 0.000 0.000 (gcc-9.3.0-ubuntu). Let's come to the point, it's because the type specifier becomes invalid as soon as you change the datatype from double to long long. You need %lli to print long long.

Why would using type double be better than long long when the size in terms of bytes is similar?

The reason is that unsigned long long will store exact integers whereas double stores a mantissa (with limited 52-bit precision) and an exponent. Its capability's dependent upon the system arch.

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

Yes, it's valid. If you don't explicitly make one of the double, then integer arithmetic will take place.

Upvotes: 1

chux
chux

Reputation: 153457

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\n", 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.

Upvotes: 1

Related Questions