Sunday, May 4, 2014

C Language - Magic of 0.7

Today, let us learn some interesting things of if-else statement of C language.

How if - else statement works

Example 1:
main()
{
int n=10;
if(n==10)
{
      printf("Hello");
}
else
{
     printf("Hi");
}
}

In the above example, execution control will check the condition (n==10) of if statement,
 since the condition of if-statement is true and therefore it will execute 
          printf("Hello"); statement. Final output of program becomes 

output : Hello

But now i am interested in comparison of floating values as given below.

Example 2:

main()
{
 float n=2.5;
if(n==2.5)
{
printf("Hello");
}
else
{
printf("Hi");
}
}

Guess the output of above program .........................
.
.
.
.
.
.
.
.
YES the answer is 
.
.
.
.
Hello
Basic Explanation

whenever any floating constant is written in program, the default data type used to hold floating constant is always double and therefore in the above case the data type of variable 'n' is float but the data type of floating constant value- 2.5 is double.

float data type allocates 4 bytes of memory to variable where as  double allocates 8 bytes of memory.

But this explanation has no impact on the output of above program, this will help you to understand the concept of next program.

Example 3: 
main()
{
float n=0.7;
if(n==0.7)
{
printf("Hello");
}
else
{
printf("Hi");
}
}

Now, guess the output of above program....
.
.
.
.
.
.
.
.
NO..........Your answer is Hello and that is incorrect.

Output of this program is 
.
.
.
Hi

Let us learn some basic concepts...
float variable 'n' is allocating 32 bits of memory in which it holds 0.7 value in binary format within 32 bits
and the equivalent decimal value of stored binary in memory is 

6.99999988079071044921875E-1

Constant value 0.7 written within the condition of 
if- statement is allocating 64 bits of memory due to its double data type. Equivalent decimal value of stored binary (64 bits binary) in memory is 

6.99999999999999955591079014994E-1

First value (6.99999988079071044921875E-1) is less than the second value (6.99999999999999955591079014994E-1) due to which condition of if-statement returns false.

To solve this problem, there are different solutions.

Solution 1: write suffix f with constant value 0.7.

float n=0.7;
if(n==0.7f)

Solution 2: Use  double data type.

double n=0.7;
if(n==0.7)

More Knowledge

This is not the case with only 'C' language but it is the basic concept of default data type in C/C++/Java i.e you will see this problem in C/C++/Java and other programming languages also this is not the case with only 0.7.

Try to test other floating values also ....


BEST OF LUCK


 
 
 
 
 







No comments:

Post a Comment