• 13
• 15
• 27
• 9
• 9

C++ Help, won't display 0

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

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 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 on other sites
The problem is probably that it isn't actually exactly equal to 30. It looks like you are using floating point numbers, and the chances are that the computation that calculates the value isn't an exact value computation.

What Every Computer Scientist Should Know About Floating-Point Arithmetic.

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?.