Silviutz
Silviutz

Reputation: 73

Issue with multiplication in C

I have this code:

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



int main(){

char name[]="g9.59e10.01024";
int a = atoi(&name[1]);
int b = atoi(&name[3]);
int c = atoi(&name[6]);
int d = c-2;
int e = pow(10,d);
int f = (100*a+b);

printf("%d",a);
printf("\n");
printf("%d",b);
printf("\n");
printf("%d",c);
printf("\n");
printf("%d",d);
printf("\n");
printf("%d",e);
printf("\n");
printf("%d",f);
printf("\n");


float mass_gal = e*f;



printf("%f",mass_gal);
printf("\n");

}

And when I run it i get this output:

9, 59, 10, 8, 100000000, 959, 1410719488.000000

All the number seems to be right, except the last one which should be 95900000000. Why do I get a wrong number there?

Thank you!

Upvotes: 0

Views: 216

Answers (2)

2501
2501

Reputation: 25752

The multiplication in the line float mass_gal = e*f; happens using integer arithmetic. The result is larger than INT_MAX and it overflows (causing undefined behavior). Then the result is converted to and stored in a float.

Cast the operators to float before performing multiplication.

float mass_gal = (float)e * (float)f;

The result will not be accurate as the IEEE 754 single precision floating point arithmetic can only accurately represent integers up to the value 2^24.

If you don't want to worry about precision, use an integer type that can represent the result, like a long long int.

Upvotes: 4

ManKeer
ManKeer

Reputation: 543

Would you please change the type from float to long and check the result, It seems that the problem with the size of the float.

Upvotes: 0

Related Questions