【问题标题】:setprecision(2) value not working in if statement even when the conditions are true [duplicate]即使条件为真,setprecision(2) 值在 if 语句中也不起作用[重复]
【发布时间】: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


【解决方案1】:

线

quotient = x / y;

0.0的值赋给变量quotient,因为2/30,使用整数除法的规则。因此,如果用户输入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 倍数。

但是,您应该知道这些操作可能会引入轻微的floating-point inaccuracies。出于这个原因,最好不要在比较中要求完全匹配

if (quotient == answer)

但考虑到高达0.01 的偏差仍被视为匹配。例如,您可以通过将表达式更改为此:

if ( std::abs( quotient - answer ) < 0.01 )

请注意,您必须#include &lt;cmath&gt; 才能使用std::roundstd::abs

【讨论】:

  • 我现在将 x 和 y 更改为浮动,但是就像您所说的那样,它不起作用。有没有办法将商的值仅更改为小数点后 2 位?因为我正在制作一个游戏,你将解决算术方程,但只有一些除法问题,答案是无限的或太长。任何解决方案?
  • @ErvinPejo:我现在编辑我的问题以提供更多信息。我相信这些附加信息可以回答您在之前的评论中提出的问题。
猜你喜欢
  • 1970-01-01
  • 2023-01-07
  • 2016-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多