【发布时间】:2022-11-12 03:41:52
【问题描述】:
我不明白为什么 setprecision(2) 在使用 if else 语句时不起作用
我尝试这样做,它显示了 else 语句。我没有看到任何问题,也许我使用 setprecision() 错误?我什至显示了商来证明 if 语句应该是运行的。
#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;
}
【问题讨论】:
-
您是否期望
setprecision更改quotient的实际值? -
我现在将 x 和 y 更改为浮点数据类型,但它仍然不会执行 if 语句...
-
是的,我想更改商的实际值。只是存在一些除法问题,答案是无限的,所以我需要避免这种情况,并认为 setprecision 是正确的做法
-
@ErvinPejo 不,您误解了
setprecision的作用。它改变了数字的打印方式,而不是计算的方式。
标签: c++ if-statement visual-c++ iomanip