Thread: Strange result when comparing two doubles

  1. #1
    Registered User
    Join Date
    Dec 2001
    Posts
    15

    Strange result when comparing two doubles

    Code:
    #include <iostream.h>
    
    void main(void)
    {
    	double num=0;
    	for(int i=0; i<10; i++)
    		num += 0.1;
    	if(num==1.0)
    		cout << "Final number is 1";
    	else 
    		cout << "Huh?";
    }
    Huh?

    Am I doing something really stupid, is my computer about to implode, or is something more subtle going on here?

  2. #2
    Mmm. Purple.
    Join Date
    May 2002
    Posts
    154

    Talking lol

    i found your answer to approximate...

  3. #3
    Registered User
    Join Date
    Dec 2001
    Posts
    15
    > void main(void)
    Get a better book - main returns an int

    1. Regardless of what ANSI may think, main returns whatever you declare it to return.
    2. The reasons for returning an int (DOS and its return codes, shells, and purely sequential execution) are long dead and decomposing in their graves.
    3. I pity the fool who actually compiles and links this snippet, then calls it from within their own console app and expect to return them a magic number.



    It might look like 0.1 when you print it out, but that too is an approximation to its true value (which is approximately 0.1)
    But I checked it on the debugger, and num's exponent/mantissa checks out to exactly one....

  4. #4
    Fingerstyle Guitarist taylorguitarman's Avatar
    Join Date
    Aug 2001
    Posts
    564
    Salem is correct but here's a link for you to look at that might explain things more in detail.
    http://www.adtmag.com/joop/crarticle.asp?ID=396
    If a tree falls in the forest, and no one is around to see it, do the other trees make fun of it?

  5. #5
    Registered User
    Join Date
    Dec 2001
    Posts
    15
    Thanks, but I'm still confused... But in the article you're dealing with numbers that clearly are distinct, ie their significant figures are different. But here, 1.0 and num have identical digits... as far as I can tell, num = 1.0000000000000 exactly.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 10-18-2006, 03:14 PM
  2. Problems with doubles
    By molistok in forum C++ Programming
    Replies: 6
    Last Post: 08-01-2006, 11:39 AM
  3. Replies: 1
    Last Post: 07-31-2006, 02:57 PM
  4. strange result of after compiling a program
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 04-23-2002, 09:54 AM
  5. bcc32 compiling error (really strange!!)
    By jester in forum C++ Programming
    Replies: 14
    Last Post: 01-26-2002, 04:00 PM