-4

Why the output is not as expected?

#include <stdio.h>
void main(){
    float a,b,c;
    b=0.7;
    if( b<0.7 )
        printf(" It should NOT be here");
    else
        printf("It Should be here");
}
Bo Persson
  • 90,663
  • 31
  • 146
  • 203

3 Answers3

0

0.7 is double value. Try 0.7f in code. It should work.

Ganeshdip
  • 389
  • 2
  • 10
  • No, seems You don't understand floating point behaviours. Is 0.69999999999999996 or 0.699999988 depends on declaration – Jacek Cz Sep 09 '17 at 08:37
  • b is a float; 0.7 is a value of type double. The comparison between the two requires a conversion. The compiler will convert the float value to a double value ... and the value resulting from converting a float to a double is not the same as the value resulting from the compiler converting a string of text (the source code) to a double. But don't ever compare floating point values (float, double, or long double) with ==. – Ganeshdip Sep 09 '17 at 08:41
  • 1
    @JacekCz - I tried this code with 0.7f and it works. Please try by yourself. It should work. – Ganeshdip Sep 09 '17 at 10:03
  • @RudyVelthuis but type should be same. Float should be compared with float. – Ganeshdip Sep 09 '17 at 18:42
  • @Jaczek: If the conversion is correct, the value in `b` should be equal to `0.7f`: `b = 0.7f; if (b < 0.7f)`. – Rudy Velthuis Sep 09 '17 at 18:43
  • @Ganeshdip: I misunderstood your comment, sorry. You answer is a little short, but correct. – Rudy Velthuis Sep 09 '17 at 18:46
  • @RudyVelthuis That's ok :) – Ganeshdip Sep 09 '17 at 19:54
-1

Floating point numbers

So behaviour You are surprised

Jacek Cz
  • 1,872
  • 1
  • 15
  • 22
  • 1
    FWIW, `0.7` (double) is exactly `0.6999999999999999555910790149937383830547332763671875`, while `0.7f` (float) is exactly `0.699999988079071044921875`. So the float is slightly smaller than the *double* representation of `0.7`. – Rudy Velthuis Sep 09 '17 at 18:37
-1

Please Try the below Code, it works!!!:

Code

 #include <stdio.h>

    int  main(void)
    {

    float a,b,c,temp;
    temp=0.7;
    b=0.7;

    if( b<temp )
        printf(" It should NOT be here");
    else
        printf("It Should be here");


    }