-3

A friend showed me this c-language code, and I'm very confused with its output. Can any one please explain why is it giving output "It was a piece of black forest cakeThis is weird", instead of "It was a piece of black forest cakeIt was a piece of black forest cake"?

# include <cstdio>

using namespace std;

int main()
{
    float a = 0.5;

    if(a < 0.5) 
        printf("This is Weird");
    else 
        printf("It was a piece of black forest cake");

    float b = 0.7;
    if(b < 0.7)
        printf("This is Weird");
    else 
        printf("It was a piece of black forest cake");

    return 0;
}
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Taha Rushain
  • 635
  • 1
  • 9
  • 26
  • 5
    Many, many duplicates, e.g. [Floating point comparison \`a != 0.7\`](http://stackoverflow.com/questions/6883306/floating-point-comparison-a-0-7) and [strange output in comparison of float with float literal](http://stackoverflow.com/questions/1839422/strange-output-in-comparison-of-float-with-float-literal) - please do a search before posting. – Paul R Aug 24 '13 at 15:00
  • 1
    Floating point precision… Computers are finite… Yadda yadda yadda. – Dave Aug 24 '13 at 15:01
  • 3
    Why don't you just do a little search on StackOverflow ? Such questions are asked daily a dozen number of times. – P0W Aug 24 '13 at 15:01
  • 2
    Sorry people . Next time i will make a search first – Taha Rushain Aug 24 '13 at 15:11
  • A five-question quiz in the same vein. If you get the first four right you have understood: http://blog.frama-c.com/index.php?post/2011/11/08/Floating-point-quiz – Pascal Cuoq Aug 24 '13 at 16:01

1 Answers1

3

This is because 0.5 can be presented as a float exactly, whereas 0.7 cannot. Also both of these are double constants, that is, to store them at their standard precision, they need to be stored in a variable of type double. YOu can get a float constant by suffixing the number with f. Furthermore in if (b < 0.7) comparison the float is converted to double implicitly; 0.7 can be stored as a double more precisely, and thus in this case is a larger number, because the 0.7 was rounded down when stored in a float variable.

Try also the following code:

#include <stdio.h>

int main()
{   
    if (0.7f < 0.7) {
       printf("This is Weird");
    }
    return 0;
}