I dont understand why setprecision(2) not working when using if else statement
I tried doing this and it displays the else statement. I dont see any problem, maybe im using setprecision() wrong? I even displayed the quotient to prove that the if statement should be the one running.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float x = 2;
float y = 3;
float quotient, answer;
quotient = x / y;
cout << fixed << setprecision(2);
cout << quotient << " (is the answer)\n";
cout << " What is " << x << " divided by " << y << " ? ";
cin >> answer; // answer should be 0.67
if (quotient == answer)
cout << " You got the right answer! ";
else
cout << " Nice Try :( ";
return 0;
}
The line
will assign the value of
0.0to the variablequotient, because2/3is0, using the rules of integer division. Therefore, if the user enters0.67, this value will not compare equal to0.0.If you want the division
2/3to evaluate to something like0.6666666667, then you must make at least one of the operands a floating-point number, for example by using a cast:However, even if you did this, your comparison would still not work, because the expression
will only change the way the variable
quotientis 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 of0.01, then you will first have to multiply the number by100before performing the rounding operation. If you want, you can then divide the number by100again, to get the original number again, rounded to the nearest multiple of0.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
but to consider a deviation of up to
0.01to still be considered a match. You can do this for example by changing the expression to this:Note that you will have to
#include <cmath>in order to usestd::roundandstd::abs.