【问题标题】:Error Correction for wrong Output错误输出的纠错
【发布时间】:2015-11-13 08:21:37
【问题描述】:

我的程序请求两个变量:一个整数和一个浮点数。两者都必须大于 0 且小于 2000。但测试 45 和 0 的输入时,它会接受该值并显示 0.00 的输出,尽管条件需要 (cash > 0) && (balance > 0)

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int cash;
    float balance ;
    cin >> cash >> balance;
    if((cash%5==0) && (cash <= balance) && (cash > 0) && (balance > 0) && (cash <= 2000) && (balance <= 2000))
    {
        balance = (balance - cash) - 0.50;
        cout << fixed;
        cout.precision(2);
        cout << balance;
    }
    else if (cash%5 != 0)
    {
        cout << fixed;
        cout.precision(2);
        cout << balance;
    }
    else if (cash > balance)
    {
        cout << fixed;
        cout.precision(2);
        cout << balance;
    }
    return 0;
}

【问题讨论】:

  • 您的代码没有输入第一个if。它进入最后一个,即else if (cash &gt; balance)。这不是故意的吗?
  • 投票结束,为什么这段代码不起作用。请使用 printfs 观察程序状态,然后生成问题的最小示例。

标签: c++ error-correction


【解决方案1】:

表达式 (cash &lt;= balance) 中的条件为假,因此它不会检查其他条件并跳转到 else 部分,并且 cash &gt; balance 满足,因此它将执行 cash &gt; balance 部分中的表达式。 例如

 int a=1,b=2,c=3;
 if((cout<<"first ") && ( a==2 ) && (cout<<" second\n"))
 {
    cout<<"condition true\n";
 }
 else
 {
    cout<<"condition false\n";
 }

这里first 将打印,当a==2 表达式出现时它是假的,所以它会移动到else 部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多