![]() |
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 : :
The program always evaluates (C==1.0) as false. Why? |
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() { |
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).
|
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