Here is a code I wrote:
#include <stdio.h>
#include <stdlib.h>
int main()
{
double num;
int tmp;
printf("enter a number!\n");
scanf("%lf",&num);
tmp=num*10000;
printf(" temp=%d\n",tmp);
return 0;
}
When I enter the number 1441.1441 the result i’m getting is 14411440 instead of
14411441 which is obviously the correct result after multiplying my input number by 10000. Can someone help me figure out this problem?
Since the vast majority of real numbers cannot actually be represented exactly, you’ll probably find that
1441.1441is actually stored as something like1441.14409999_blah_blah_blah. You can find that out by inserting:immediately after the
scanfand seeing (trailing zeroes removed):Now that’s actually the correct (ie, closest) value based on your input. The next highest number from there gives you:
The error with the first value is:
while the error with the second is:
and you can see the latter error is about 10 times as much.
When you multiply that by
10000and try to shoehorn it into anint, it gets rounded down (truncated). That’s because the (C11) standard has this to say in6.3.1.4:One thing you can try is to change your shoehorning line into:
which effectively turns the truncation into a rounding operation. I think that will work for all cases but you may want to test it (and keep an eye on it) just in case.