HomeComputer programmingC programmingTwo Common Mistakes in Floating Point Arithmetic in C

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.

Vishwanath Dalvi
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.
RELATED ARTICLES

3 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments

Cleveland Furia on How to Clear Google Activity
Sid Wohlfarth on How to Clear Google Activity
Riley Magsayo on How to Clear Google Activity
สมัครรับเครดิตฟรี ทันที on How to improve Remote Desktop Protocol Performance
Neal Wangstad on How to Clear Google Activity
Slavcho Andov on How to install Ubuntu
Slavcho Andov on How to fix bad sectors
Sheraz Ali on How to Backup Android