0

So i have got a problem with floating point variables. can someone explain? the code is given below...

#include<stdio.h>

void main() {
    float b=3.6;
    if(b==3.6)
    {
        printf("one");
    }
    if(b<=3.6)
    {
        printf("two");
    }
    if(b>=3.6)
    {
        printf("three");
    }
    else printf("four");
}

Now why is the Output "two" and "four"? and how do i avoid such things in pprograms?

Dair
  • 15,910
  • 9
  • 62
  • 107
Sam
  • 69
  • 1
  • 4
  • 12

1 Answers1

0

You are comparing floats to doubles. Try comparing them to 3.6f instead of 3.6

Jcl
  • 27,696
  • 5
  • 61
  • 92
  • by default does it take 3.6 as double when comparing? – Sam May 17 '14 at 06:26
  • You might want to check this: [What's the point of the L, U and f suffixes on numeric literals?](http://www.parashift.com/c++-faq-lite/numeric-literal-suffixes.html) – Jcl May 17 '14 at 06:29
  • And answering to your comment... yes, every unsuffixed literal with decimals is taken as a `double`, so it's actually promoting `b` to `double`, and making the comparison afterwards – Jcl May 17 '14 at 06:31