提问人:Ervin Pejo 提问时间:11/12/2022 最后编辑:Ervin Pejo 更新时间:11/12/2022 访问量:106
setprecision(2) 值在 if 语句中不起作用,即使条件为 true [duplicate]
setprecision(2) value not working in if statement even when the conditions are true [duplicate]
问:
我不明白为什么 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;
}
答:
0赞
Andreas Wenzel
11/12/2022
#1
线
quotient = x / y;
将 的值赋值给变量 ,因为 是 ,使用整数除法规则。因此,如果用户输入 ,则此值不会等于 。0.0
quotient
2/3
0
0.67
0.0
如果希望除法的计算结果类似于 ,则必须使至少一个操作数为浮点数,例如使用强制转换:2/3
0.6666666667
quotient = static_cast<float>(x) / y;
但是,即使您这样做了,您的比较仍然不起作用,因为表达式
cout << fixed << setprecision(2) << quotient;
只会更改变量的打印方式。它不会更改变量的实际值。quotient
为了舍入变量的实际值,您可以使用函数 std::round
。请注意,这只会四舍五入到最接近的整数,因此,如果要四舍五入到最接近的 的倍数,那么在执行舍入操作之前,必须先将数字乘以。如果需要,可以再次将数字除以,再次得到原始数字,四舍五入到最接近的 的倍数。0.01
100
100
0.01
但是,您应该知道,这些操作可能会引入轻微的浮点不准确。因此,最好不要在比较中要求完全匹配
if (quotient == answer)
但要考虑最多到的偏差仍被视为匹配。例如,您可以通过将表达式更改为以下内容来执行此操作:0.01
if ( std::abs( quotient - answer ) < 0.01 )
请注意,您必须使用 和 。#include <cmath>
std::round
std::abs
评论
0赞
Ervin Pejo
11/12/2022
我现在将 x 和 y 更改为浮动,但是是的,就像你说的那样,它不起作用。有没有办法将商的值更改为仅小数点后 2 位?因为我正在制作一个游戏,您可以在其中解决算术方程式,但只有一些除法问题,答案是无限的或太长的。有什么解决方案吗?
0赞
Andreas Wenzel
11/12/2022
@ErvinPejo:我现在已经编辑了我的问题以提供更多信息。我相信这些附加信息回答了您在之前的评论中提出的问题。
评论
setprecision
quotient
setprecision