0

Sometimes an if statement is executed even if the condition isn't met. The condition involves a double value:

if (percentage < 10.0) cout << " ";

I use this line of code in my program and running it should output something like this:

Frequency of outcomes: Outcome 1: 10.08 % Outcome 2: 10.15 % Outcome 3: 9.98 % Outcome 4: 10.00 % Outcome 5: 9.88 %

But this happens instead:

Frequency of outcomes: Outcome 1: 10.08 % Outcome 2: 10.15 % Outcome 3: 9.98 % Outcome 4: 10.00 % Outcome 5: 9.88 %

As you can see, even though 10.00 is not less than 10.00, the if statement executes anyway. Why does this happen?

This is my code: http://codepad.org/Ikt85kZc

  • 1
    Your value of 10.00 is probably something like 9.99999987 in reality, but you don't see this because it's getting rounded for display purposes. Look at the value in your debugger to see what it really is. – Paul R Mar 02 '17 at 09:40
  • Because you limited the precision, meaning that `9.9999 < 10` but when printed it is rounded to `10.00` which is the closest number to `9.9999` with 2 digits after the comma. – nwp Mar 02 '17 at 09:41
  • 3
    Unrelated to your problem, but why do you use output of spaces for your formatting? Doesn't e.g. [`std::setw`](http://en.cppreference.com/w/cpp/io/manip/setw) work as you expect it to? – Some programmer dude Mar 02 '17 at 09:42

0 Answers0