0

Below is the program for if and else

#include<stdio.h>
#include<conio.h>

int main()
{
    float a = 0.7; //a declared as float variable

    if(a == 0.7)  //why it takes only integral part of 0.7 
    {
        printf("Hi"); 
    }
    else
    {
        printf("hello"); 
    }

    return 0; 
}

Shouldn't this program display Hi instead of hello as 0.7 is equal to 0.7?

(I'm new to C programming)

Filburt
  • 17,626
  • 12
  • 64
  • 115
  • 1
    Don’t compare the float variable using == , because the precision of the floating point is not same. You can find plenty of questions in SO regarding floating point comparison. – danglingpointer Oct 14 '18 at 08:50
  • Don't compare floating point number like this, [use something like](https://stackoverflow.com/questions/17333/what-is-the-most-effective-way-for-float-and-double-comparison) – Raviprakash Oct 14 '18 at 08:53
  • Please see [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) and [Why Are Floating Point Numbers Inaccurate?](https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) – Weather Vane Oct 14 '18 at 09:22

2 Answers2

6

Note that

float a = 0.7;

converts a double value 0.7 to a float and then

if(a == 0.7)

converts a to a double.

Since 0.7 cannot be exactly represented in floating point, the float and double representations are not quite the same.

You can force the compiler to stay with float like this

#include<stdio.h>

int main()
{
    float a = 0.7f;
    if(a == 0.7f)
    {
        printf("Hi"); 
    }
    else
    {
        printf("hello"); 
    }
    return 0; 
}

And now the program prints "Hi" because it is comparing like with like.


More generally you must be very wary of floating point comparisons for equality

#include<stdio.h>

int main()
{
    double d = 2.1;
    d /= 3.0;
    if(d == 0.7) {
        puts("Equal");
    }
    else {
        puts("Unequal");
    }
    printf("%.17f\n", d);
    printf("%.17f\n", 0.7);
    return 0; 
}

Program output

Unequal
0.70000000000000007
0.69999999999999996
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
1

If you change datatype of a to double, it'll print hi, This is because constants in floating point stored in double and non floating in long, double precision is high and float has less precise, double value stored in 64 bit binary and float value stored in 32 bit binary, it'll be completely clear if you see the method of floating point numbers conversion to binary convertion.

Muhammad Azam
  • 535
  • 7
  • 12