Thread: why the control goes to else part in this program

  1. #1
    Registered User
    Join Date
    Aug 2008

    why the control goes to else part in this program

            float flt 1.1;
            double dbl 1.1;
             if(flt == dbl) 

    In this program when we run it, it goes to the else part and prints hello....
    but in this same case if the value is changed of both double and float variables it works properly printing hi.....

    what is the reason for that?????

  2. #2
    verbose cat
    Join Date
    Jun 2003
    The computer stores an integer variable (char, short, int, long, etc.) in a simple binary format that is exact. If you assign a value of 1 to an int variable, it will be represented as exactly 1.

    The computer stores float and double variables in a different format that makes it possible to work with decimals, like 1.1, but at the cost of accuracy. The internal format of a float is complicated, and uses different parts of the variable differently, unlike int variables. When you assign a float variable to the value 1.1 for example, the internal representation may store it as 1.0999999237, or 1.10000001, but not 1.1.

    The bottom line to you, the programmer, is that you can not reliably compare 2 float values, 2 double values, or a float and a double using ==. Even though it appears to work when you change both variables to float, or both variables to double, you should not use == with floats or doubles. Your compiler may generate instructions that work in a specific situation, but if you use a different compiler, or someone else tries to compile your program with a different compiler, even that will probably fail.

    This site (first hit in a Google search for "compare float values") should help.
    abachler: "A great programmer never stops optimizing a piece of code until it consists of nothing but preprocessor directives and comments "

  3. #3
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    in front of my computer
    see on floating point numbers

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Program to control Cursor movement in C
    By beginner in forum C Programming
    Replies: 2
    Last Post: 06-25-2011, 11:20 AM
  2. Get a window handle for control of other program
    By Kirdra in forum Windows Programming
    Replies: 3
    Last Post: 01-10-2009, 08:52 PM
  3. Problem with part of program
    By ammochck21 in forum C++ Programming
    Replies: 8
    Last Post: 11-09-2006, 06:45 AM
  4. help with letter counting part of program
    By bluegoo06 in forum C++ Programming
    Replies: 7
    Last Post: 04-26-2005, 08:25 PM
  5. How do you branch to another part of the program?
    By gcn_zelda in forum C++ Programming
    Replies: 3
    Last Post: 03-16-2003, 12:27 PM