float amount;
printf("Enter the amount:\n");
scanf("%f", &amount);
// input: 100.10
printf("%f", amount);
Output: 100.099998
The problem is that the output is not 100.10 same as the input;
float amount;
printf("Enter the amount:\n");
scanf("%f", &amount);
// input: 100.10
printf("%f", amount);
Output: 100.099998
The problem is that the output is not 100.10 same as the input;
Floating point numbers like 100.10
has no exact binary representations. That's why you encountered rounding error.
Note that there is something more behind, %f
in printf
actually expects a double
argument, so here amount
is converted to double
in the printf
call.
The reason is, variable argument functions like printf
always promote their variable argument parts, that's why printf
has no format specifier for float
, because it always sees double
. So a better program to demonstrate your question is to use double
instead:
double amount;
printf("Enter the amount:\n");
scanf("%lf", &amount);
printf("%f", amount);
You'll still get rounding error, but no conversion from float
to double
is done. And to demonstrate the program, you may need to print more digits as double
is more accurate.