The line
quotient = x / y;
will assign the value of 0.0
to the variable quotient
, because 2/3
is 0
, using the rules of integer division. Therefore, if the user enters 0.67
, this value will not compare equal to 0.0
.
If you want the division 2/3
to evaluate to something like 0.6666666667
, then you must make at least one of the operands a floating-point number, for example by using a cast:
quotient = static_cast<float>(x) / y;
However, even if you did this, your comparison would still not work, because the expression
cout << fixed << setprecision(2) << quotient;
will only change the way the variable quotient
is printed. It will not change the actual value of the variable.
In order to round the actual value of the variable, you can use the function std::round
. Note that this will only round to the nearest integer, so if you want to round to the nearest multiple of 0.01
, then you will first have to multiply the number by 100
before performing the rounding operation. If you want, you can then divide the number by 100
again, to get the original number again, rounded to the nearest multiple of 0.01
.
However, you should be aware that these operations may introduce slight floating-point inaccuracies. For this reason, it may be better to not require an exact match in the comparison
if (quotient == answer)
but to consider a deviation of up to 0.01
to still be considered a match. You can do this for example by changing the expression to this:
if ( std::abs( quotient - answer ) < 0.01 )
Note that you will have to #include <cmath>
in order to use std::round
and std::abs
.