Click here to Skip to main content
14,638,817 members
Rate this:
Please Sign up or sign in to vote.
See more:
#include <conio.h>
#include <stdio.h>
#define pf printf
void main()
{
   float me = 0.7;
   double  you = 0.7;
   clrscr();
   if (me == you)
   {
	printf("I like this ");
   }
   else
   {
	printf("I don't like this");
   }
   getch();
}


What I have tried:

here the output come I don't like this but the value of me and you variable is same so why does it happen?
I change the data type of variable

int   me = 7;
float   you = 7;
clrscr();
if (me == you)
{
 printf("I like this ");
}
else
{
 printf("I don't like this");
}


here the if condition is true and the output is I like this.
can you explain me why?
Posted
Updated 1-Jun-18 21:49pm
Rate this:
Please Sign up or sign in to vote.

Solution 1

Quote:
here the output come I don't like this but the value of me and you variable is same so why does it happen?

The values are not same because of data type difference.
Double and float are floating point, so 0.7 are approximated in both types, but with a little difference which remains when float is expended to double, enough to make the test fail.

In second code, when test is done, the int is expended to float and give exact same value.
   
Comments
An@mik@ 2-Jun-18 3:48am
   
How can we check the approximate value ? I debug in c editor but it only show the assign value.
Patrice T 2-Jun-18 3:53am
   
Since conversion is done on fly in test, you need to debug at assembly level to see something, and you may also need to display value as binary to see its internal value.
Rate this:
Please Sign up or sign in to vote.

Solution 2

Because of the different data type the values are very slightly different. You should calculate the difference and check that its value very tiny.
double diff = me - you;
if( abs( diff ) < 0.00001 )
Use abs for comparision. The 0.00001 value I have choosen by experience.
   
Comments
An@mik@ 2-Jun-18 3:53am
   
Ok thanks

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100