Nikitas Nikitas - 3 months ago 8
C Question

How to multiply floating point in ANSI C?

The following code:

float numberForFactorial;
float floatingPart = 1.400000;
int integralPart = 1;

numberForFactorial = ((floatingPart) - (float)integralPart) * 10;

printf("%d", (int)numberForFactorial);


Returns 3 instead of 4. Can you explain me why?

Answer

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.