Click here to Skip to main content
15,889,698 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include<stdio.h>
int main()
{
if(2==45.000/22.5)
printf("%d",1);

return 0;
}
the following program printed 1.
so is 2==2.0 treated as true in c language.
if its true what if i write 2==(a/b)
where a/b turns out to be something like 2.00000005
and if my compilers precision is upto 6 decimals then will it be treated as true?
#include<stdio.h>
int main()
{
if(2==2.000000000001)
printf("%d",1);

return 0;
}
this is not printing anything but if i type 2==2.000000000000000000000001 then 1 is being printed.

thanks
Posted
Updated 8-Feb-15 18:49pm
v2

1 solution

It's down to precision.
When you use == to compare two values, they have to be exactly the same to match: so you wouldn't expect something along the lines of "hello there." to exactly match "hello there!" and when you come to numbers it's the same.
when you compile
C++
if(2==45.000/22.5)
The compiler looks at teh code and:it to
45.000 - floating point constant value, 45.0
22.5   - floating point constant value, 22.5
So change to constant value: 45.0/22.5
C++
if(2==2.0)

2 integer constant value: cast to floating point constant value, 2.0

C++
if(2.0==2.0)

constant comparison: evaluate - true. Remove comparison if optimized


When you compare the next values
C++
if(2==2.000000000001)

2.000000000001    - floating point constant value, 2.000000000001
2                 - integer constant value, cast to float 2.0

C++
if(2.0==2.000000000001)

constant comparison: evalutate - false. Remove comparison if optimized

When you try your third:

C++
if(2==2.000000000000000000000001)

The same thing happens, but when it evaluates 2.000000000000000000000001 as a floating point number there aren't enough digits places in the binary representation of a floating point number to include the trailing "1" so it evaluates as 2.0.

A floating point number has to fit inside a 32 or 64 bit (sometimes 128 bit) binary value, and if there aren't enough bits to fit, it will be truncated.

There is a good (if technical) description on Wiki: Single-precision_floating-point_format[^]
 
Share this answer
 
Comments
Member 11324568 9-Feb-15 9:32am    
That's an awesome explanation..thanks a lot original Griff ..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900