Sign in to follow this  
Sonic71089

C++ Help, won't display 0

Recommended Posts

I'm writing a program that calculates QB Rating. This part of the code works besides it won't display a 0 when equal to 30. completepercent = ((completions / attempts) * 100); if (completepercent <= 30) completerating = 0; else if (completepercent > 77.5) {completerating = 2.375;} else {completerating = (completepercent - 30) * .05;} cout << completerating; It's the if(completepercent <= 30) completerating =0 part that isn't working. If the completepercent is equal to less than 30 it displays correctly as a 0 but when it is equal to exactly 30 it displays 8.67362e-020 when it should still be displaying a 0. What is the problem?

Share this post


Link to post
Share on other sites
The problem is that instead of being equal to 30, the value is slightly larger than 30 (by a very small value, possibly smaller than a billionth of a billionth), and thus the "(completepercent - 30) * 0.05" part gets executed instead, which results in a very small value.

You can either accept this as reasonable error (because, after all, the result is so close to zero that it's not noticeable if you display your values correctly), or correct the test so that you trigger on being smaller than 30 + epsilon, for a correct value of epsilon (one millionth sounds good in general when working with percentages).

By the way, unless I'm mistaken, your code can be expressed as:

completepercent = ((completions / attempts) * 100);
completerating = std::max (0.0, std::min(2.375, (completepercent -30) * 0.05));

Share this post


Link to post
Share on other sites
I ran into a similar problem with my C++ pi calculation program a while back and used the following code to help me compare small floating point numbers:

inline bool isEqual(double x, double y)
{
const double epsilon = /* some small number such as 1e-5 */;
return std::abs(x - y) <= epsilon * std::abs(x);
// see Knuth section 4.2.2 pages 217-218
}

which I found here under [29.17] Why doesn't my floating-point comparison work?.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this