problem with floats in conditional statements

This is a discussion on problem with floats in conditional statements within the C Programming forums, part of the General Programming Boards category; If I recall, there's a problem comparing floats for equality because of how they are stored and computed. They are ...

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    903
    If I recall, there's a problem comparing floats for equality because of how they are stored and computed. They are not exact values; hence the inequality. I would substract both numbers together and check if the difference is in a certain range like this:
    Code:
    #define MIN_MAX_RANGE 0.01f
    
    // ...
    
    float a = 12.345f;
    float b = 12.345f;
    if(std::abs(a - b) <= MIN_MAX_RANGE)
        // do something

  2. #2
    Registered User
    Join Date
    Jun 2006
    Posts
    12

    problem with floats in conditional statements

    Code:
    #include<stdio.h>
    
    int main()
    {
          float a=0.7;
     
          if( a<0.7)          // 
                 printf("true\n");
          else
                 printf("false\n");
    }
    here a=0.7 is not obviously less than 0.7...
    Logically the output should be printed as "false", but its being printed as true...
    i am not able to figure out the logic.. can somebody please tell me how the statement is interpreted...

    - regards
    Abhijith

  3. #3

  4. #4
    Registered User
    Join Date
    Jun 2006
    Posts
    12

    that got posted accidently...

    sorry.. didnt realize that it got published...
    will take care next time while posting..

    sorry once again..

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. searching problem
    By DaMenge in forum C Programming
    Replies: 9
    Last Post: 09-12-2005, 01:04 AM
  2. Bin packing problem....
    By 81N4RY_DR460N in forum C++ Programming
    Replies: 0
    Last Post: 08-01-2005, 05:20 AM
  3. binary tree problem - help needed
    By sanju in forum C Programming
    Replies: 4
    Last Post: 10-16-2002, 05:18 AM
  4. multi conditional if statements?
    By chaser in forum Game Programming
    Replies: 3
    Last Post: 07-26-2002, 10:52 PM
  5. Using floats in conditional statements
    By DBB in forum C++ Programming
    Replies: 3
    Last Post: 09-12-2001, 07:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21