0

I'm facing the below problem in C & C++. The following code snippet is giving me incorrect result.

#include<stdio.h>
void main()
{
    double a=40.48;
    int b=a*10000;
    printf("The value of b : %d",b);
}

The output of the above code snippet is 404799 where I expect it to be 404800. Can you please help me explain why it is ? And guide me with necessary corrections.

The above code snippet gives me correct results if I try with other values of variable a.

For example:

#include<stdio.h>
void main()
{
    double a=40.49;
    int b=a*10000;
    printf("The value of b : %d",b);
}

The output of the above code snippet is 404900 which is absolutely correct.

So please enlighten me why the calculation is going wrong with value 40.48.

Thanks in advance.

Hasan
  • 1
  • 1
  • 2
    The link is important and worth reviewing BUT if you change int b=a*10000; to double b=a*10000; you will get the right result which seems to suggest that type conversions are causing this issue. – london-deveoper Jan 24 '17 at 06:32
  • @ccpgh, Yes, integers truncate, indicating that the real value is slightly below the one the OP anticipated. The real issue is still expecting the multiplication to be exact. It appears to work with `b` being a `double` only because `printf` rounds the value. You can [see here](http://coliru.stacked-crooked.com/a/942bc8d5905483ae) that it still isn't exact. – chris Jan 24 '17 at 14:18

0 Answers0