The float
closest to 1.400000
is slightly less than 1.4
. You can verify that by doing
printf("%0.8hf\n", floatingPart);
The result from ideone is 1.39999998
. This means that 10 times the first digit after the decimal point is 3
.
To avoid this issue, use rounding instead of truncation. One easy way to round is by adding half before truncation:
printf("%d", (int)(numberForFactorial + 0.5f));
will print 4
as you were expecting. You can also use round
, rint
, lround
, or modf
to get the same result: https://www.gnu.org/software/libc/manual/html_node/Rounding-Functions.html. Rounding is a complex topic, so choose the method whose constraints match your situation best.