-4
#include <stdio.h>
#include <conio.h>
int main()
{
int a = 8; float b = 3.9; char c='a';
float hasil = a+b+c;
printf("%f", hasil);
getch();
return 0;
}

I Get result 108.900002

then, where 0.000002 is it?

If I change to

float hasil = a+b;

then the result will be 11.900000

Then if we convert char so float, then it will definitely add value 0.000002? Is that true ? If yes why?

Thanks you

WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
  • Floating-point values are stored in binary. The values `3.9` and `108.9` cannot be represented exactly. The actual value is most likely `108.90000152587890625`. – Keith Thompson Oct 12 '16 at 23:40

2 Answers2

3

char c = 'a' assigns the value 97 to c. 97 + 8 + 3.9 is 108.9 in real numbers, but it does not have an exact representation as a float. That's where the spurious 0.000002 comes from. As Keith Thompson points out, the actual value is likely to be 108.90000152587890625, but the %f format specifier probably rounds it.

This is due to the fact that there can only be a finite number of floating point numbers whereas there are uncountably many real numbers.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
2

Neither 11.9 nor 108.9 can be represented exactly in a float. You will get better accuracy if you use double.

If you change the precision of printing, you will see how accurately those are represented.

#include <stdio.h>

int main()
{
   int a = 8; float b = 3.9; char c='a';
   float hasil = a+b;
   printf("%.16f\n", hasil);
   hasil = a+b+c;
   printf("%.16f\n", hasil);
   return 0;
}

Output:

11.8999996185302734
108.9000015258789062

By changing the type to double, I get more accurate output:

#include <stdio.h>

int main()
{
   int a = 8; double b = 3.9; char c='a';
   double hasil = a+b;
   printf("%.16f\n", hasil);
   hasil = a+b+c;
   printf("%.16f\n", hasil);
   return 0;
}

Output:

11.9000000000000004
108.9000000000000057

Those results are from gcc running on a Linux desktop. I suspect you will get similar, if not exactly same, results in other common compilers too.

R Sahu
  • 204,454
  • 14
  • 159
  • 270