-1
long long temp_number;
float input = 0.7f;
temp_number = input*100;
printf("%lld",temp_number);

Could anybody explain why do i get 69 instead of 70?

DimitriosP
  • 106
  • 1
  • 8

1 Answers1

1

There is nothing mysterious here. It is similar to writing 1/3 as a decimal 0.333333~ ( ~ meaning "recurring") and then multiplying by 3. The answer is 0.999999~ not 1, and I hope you can see this has nothing to do with computer science.

You have converted the float to long long int and the compiler warns that doing so might result in loss of data. But you multiply by 100 before converting to a different type, so let's look at the float example more.

The decimal value 0.7 cannot be exactly represented in binary float format. When you use printf with float it rounds up the least significant bit of the mantissa to deal with the problem. So when I do this

float f = 0.7f;
printf("%f\n", f);

the output is 0.700000 which I wanted. But when I multiply the float value by 100, that creates a bigger error in the least significant bit of the mantissa, which previously was only in error by 1. So now using

float f = 0.7f;
printf("%f\n", f*100);

the output is 69.999999 because rounding the least significant bit up does not make the number roll up to 70.000000.

Returning to the first example of the decimal representation of 1/3 but in a finite storage size, say 10 decimal digits as 0.333333333. Multiplying by 3 gives 9.999999999 and rounding up the last digit is will produce 1.000000000. But multiplying by 30 gives 9.999999990 and rounding up the last digit is not going to produce 10.00000000.

The C language does not "know" that the float representation of the number truncates a recurring fraction. Perhaps there is a numerical type that can hold this information and compute arithmetical functions accordingly.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • Some details: "printf with float it rounds up the least significant bit" is amiss. `printf()` rounds the x.xxxxxx result to the nearest 0-9 _decimal digit_, not _bit_. So `0.7f` or `0.6999999881...` goes to `0.700000` and `printf("%f\n", f*100);` goes to `69.999999` – chux - Reinstate Monica Jul 06 '15 at 17:19