The compiler is not doing anything wrong; this is a typical "gotcha" of floating-point arithmetic.
What's happening here is that your input values are not being stored exactly as 9.72, 9.73 and 9.74 but rather as floating-point approximations of those numbers. They are very, very close to the input values, but off by a tiny amount, and printf()
won't show the more precise value unless forced to. Try running this program:
#include <stdio.h>
int main(void)
{
float n1 = 9.72;
float n2 = 9.73;
float n3 = 9.74;
printf("9.72 times 100 is %.15f \n", n1 * 100);
printf("9.73 times 100 is %.15f \n", n2 * 100);
printf("9.74 times 100 is %.15f \n", n3 * 100);
}
You should see this output:
9.72 times 100 is 972.000000000000000
9.73 times 100 is 972.999938964843750
9.74 times 100 is 974.000000000000000
When you assign those values directly to n
, because n
only stores integer values, everything after the decimal point gets truncated - even if the number is very, very close to the next integer. So you should always be careful when casting numeric values to, or storing them in, other numeric types.
In this case you can solve your problem by making sure to round your float to the nearest integer before you store its value.
For more information about floating-point numbers, you can explore the web site What Every Programmer Should Know About Floating-Point Arithmetic.