Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   Extremely weird program behavior (http://www.programmingforums.org/showthread.php?t=15446)

Lakrids Mar 20th, 2008 7:34 AM

Extremely weird program behavior
 
Hello,

I have been programming for quite a while now, but the following behavior is one of the most weird ones I ever encountered. It really is annoying me, and I just can't get to the bottom of it. So, in short, the other day I was writing a very small program which calculates all possible solutions to a given problem. The program didn't work, and after some debugging, I was astonished that the following code just doesn't seem to work for some obscure reason. The problem is that nothing is written to the screen in the loop :

:

  1. #include <iostream>
  2.  
  3. int main() {
  4.  
  5.     for (double C=0.0; C<100.0; C+=0.1)
  6.         if (C==1.0)
  7.             std::cout << C << std::endl;
  8.  
  9.     return 0;
  10. }


The program always evaluates (C==1.0) as false. Why?

Ancient Dragon Mar 20th, 2008 8:13 AM

Re: Extremely weird program behavior
 
Never use equality == when working with doubles because as you have found out it will frequently not evaluate correctly due to the way floating point values are stored in memory. More than likely what is happening in your case is that there are some very small decimal places that you did not intend to be there.

Here's how to make it work
:

int main() {
    for (double C=0.0; C<100.0; C+=0.1)
        if( C > 1.0 && C < 1.2)
            std::cout << C << "\n";

    return 0;
}


lectricpharaoh Mar 20th, 2008 1:32 PM

Re: Extremely weird program behavior
 
To expand on what Ancient Dragon said, you need to remember that it's binary floating point. There are some numbers that cannot be exactly represented, and 0.1 is one of those (much like one-third cannot be exactly represented in decimal).

Lakrids Mar 20th, 2008 2:51 PM

Re: Extremely weird program behavior
 
Thank you!


All times are GMT -5. The time now is 12:47 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC