Two Common Mistakes in Floating Point Arithmetic in C
Posted November 2, 2011 by Vishwanath Dalvi in C programming
This tutorial will demonstrate two rules that must be respected when performing floating point arithmetic in C. Following these rules will prevent loss of information. Examples with walk through explanation provided.
1st Rule: If an arithmetic operator has integer operands then integer operation is performed.
Let’s see an example.
#include "stdio.h"
main()
{
float c;
c = 5 / 9;
printf("c = %f",c);
getch();
}
In above program, though variable c appears to have float data type, the program prints c = 0.000000. The programmer likely expected that c = 0.555556.
Reason: in this expression c = 5 / 9, the / is the arithmetic operator. 5 and 9 are the integer operands. As per the 1st Rule, integer operation is performed. Therefore, integer division truncates and any fractional part is discarded. Thus, the expression truncates to 0.
2nd Rule: If an arithmetic operator has one floatingpoint operand and one integer operand, the integer will be converted to floating point before the operation is done.
#include "stdio.h"
main()
{
float c;
c = 5.0 / 9;
printf("c = %f",c);
getch();
}
In above program, variable c has float data type and program prints c = 0.555556, excepted output.
Reason: in this expression c = 5.0 / 9, the / is the arithmetic operator, 5.0 is floatingpoint operand and 9 is integer operand. As per the 2nd Rule before the operation is done the integer operand is converted into floatingpoint operand. The expression will be c = 5.0 / 9.0. The expression is not truncated because it is the ratio of two floating point values and thus the program prints c = 0.555556.
About Vishwanath Dalvi
View more articles by Vishwanath Dalvi
The Conversation
Follow the reactions below and share your own thoughts.

rick

Evan