Two Common Mistakes in Floating Point Arithmetic in C

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 floating-point 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 floating-point operand and 9 is integer operand. As per the 2nd Rule before the operation is done the integer operand is converted into floating-point 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

Vishwanath Dalvi is a gifted engineer and tech enthusiast. He enjoys music, magic, movies, and gaming. When not hacking around or supporting the open source community, he is trying to overcome his phobia of dogs.
View more articles by Vishwanath Dalvi

The Conversation

Follow the reactions below and share your own thoughts.

  • rick

    clear, good explaination; I re-learning what I have forgotten

  • Vishwanath Dalvi

    @rick thank you!

  • Evan

    Too bad C# doesn’t have the ‘//’ (integer division) operator like Python (3K). It takes the guess work out of the equation. Less ambiguity == fewer bugs.

    Doesn’t it seem ironic that most/all statically typed languages rely on type inference to determine which division operation to use. Must be one of those legacy kickbacks that was inherited from C.