Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Orikal

Subtraction issue with double (Should be simple but it's NOT!)

This topic is 6171 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

#include using namespace std; //introduces namespace std void dosomeshit(void){ double percentDown =6.5; while (percentDown != 0) { cout << percentDown; percentDown -= 0.1; } } int main( void ) { dosomeshit(); return 0; } When you run this, the program shoots off into an infinite loop! Why? Any help would be greatly appreciated. My sanity is at sake. Thanks

Share this post


Link to post
Share on other sites
Advertisement
float and doubles implementation are approximates. So 0 is not really 0 (it may be 0.000000000000000000001 ).

The usual solution is to do greater,lesser than test instead of equality test.

Share this post


Link to post
Share on other sites
Do something like...

  
double maxDifference = 0.0001;

while((percentDown - valueYouCompareWith) < maxDifference)
{
...
}

But in this case valueYouCompareWith is zero so you can leave it out. I think the compiler does so too, as an optimisation.
If the other value could be greater, also do an absolute value, cause you could get negative values.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!