strange error with in C program

5 replies [Last post]
anish
Offline
Last seen: 10 years 17 weeks ago
Joined: 2009-04-08
bOt Points: 94

i encountered this strange problem whie dealing with floating point numbers

 

#include <stdio.h> int main()

{

float num=1.0f;

num+=0.1f;

if(num==1.0)

printf("%f = 1.1",num);

else

printf("%f != 1.1",num); }

 

 

the output is:

1.1 !=1.1

cardcaptor sakura
Offline
Last seen: 10 years 16 weeks ago
Joined: 2009-06-23
bOt Points: 66
see your programme is

see

your programme is calculating num as 1+.1 in 3rd line

 

so in fourth line it is seeing num!=1.0

thus giving the output 

anish
Offline
Last seen: 10 years 17 weeks ago
Joined: 2009-04-08
bOt Points: 94
misprinting :(

Aplologies for posting the wrong code

 

the actual code was

#include <stdio.h>
int main()
{
float num=1.0f;
num+=0.1f;
if(num==1.1)
printf("%f = 1.1",num);
else
printf("%f != 1.1",num);
return 0;
}

shanwadnaveen
Offline
Last seen: 10 years 17 weeks ago
Joined: 2009-06-24
bOt Points: 54
cause

in if condition the num is getting a value of 1.10000 and we are comapring it with 1.1.. so it is displaying the other result.. the solution to this is take the value 1.1 into an variable which is of floating type.. and compare with num.. you will get result.

 

#include <stdio.h>

int main()

{

float num=1.0f,k=1.1;

num+=0.1f;

if(num==k)

printf("%f = 1.1",num);

else

printf("%f != 1.1",num);

return 0;

}

shubham
Offline
Last seen: 7 years 12 weeks ago
Joined: 2009-05-28
bOt Points: 134
It Works!

It works...

anish
Offline
Last seen: 10 years 17 weeks ago
Joined: 2009-04-08
bOt Points: 94
In that case why does the

In that case why does the following code also produce erroneous output

 

#include <stdio.h>

int main()

{

float num=1.0f;

num+=0.1f;

if(num==1.100000)

printf("%f = 1.100000",num);

else

printf("%f != 1.100000",num);

return 0;

}