【问题标题】:If else positionIf else 位置
【发布时间】:2014-08-27 01:56:45
【问题描述】:

我正在尝试用 C++ 为一个程序编写代码,该程序提示用户输入两个数字并求和、差、积和商。该程序应该让您知道它不能被零除。这是我目前的代码。

#include <iostream>
using namespace std;

int main() {
    double a; //using double will allow user to input fractions 
    double b; //again using double will allow the user to input fractions
    double sum, diff, prod, quot; //these variables will store the results

    cout << "Enter a number: ";
    cin >> a;
    cout << "Enter another number: ";
    cin >> b;

    //Operations variables
    sum        = a + b;
    diff       = a - b;
    prod       = a * b;


    //Conclusion
    cout << "Sum is: " << sum << endl;
    cout << "difference is: " << diff << endl;
    cout << "product is: " << prod << endl;

    if (b == 0) {
        cout << "quotient is undefined";
    }
    else {
        quot        = a/b;
    }

    cout << "quotient is: " << quot << endl;

    return 0;
}

此代码编译并运行。我似乎遇到的唯一问题是我的 if else 语句的位置。我尝试了多个位置。 如果我让第二个数字= 0,我得到的输出如下

Enter a number: 12
Enter another number: 0
Sum is: 12
difference is: 12
product is: 0
quotient is undefinedquotient is: 0

如果 b 为零,我如何让它只说未定义,如果 b 不为零,则给出答案。

【问题讨论】:

  • 如你所愿,涉及quot 的输出总是被执行。您希望它有条件地执行。它恰好与以前使用的条件相同。
  • 我认为这是学习如何使用步进调试器的好机会。即使您还没有足够的经验来确定检查时哪里出了问题,但如果您在调试器中单步执行该程序,就会清楚地知道发生了什么以及原因。

标签: c++ if-statement zero divide-by-zero


【解决方案1】:

问题是你的最后一个cout 应该在else 块内:

cout << "quotient is";
if (b == 0) {
    cout << " undefined";
} else {
    quot = a/b;
    cout << ": " << quot;
}
cout << endl;

正如所写,您的"quotient is: " &lt;&lt; quot 在每种情况下都在执行,但您实际上只希望它在b == 0 评估为false 时执行。

【讨论】:

  • 我可能也会在第一个 cout 上添加一个 &lt;&lt;endl
  • @pqnet 还是在整个区块之后只做一次?
【解决方案2】:

将最后一个 cout 移动到 else 块中。

【讨论】:

    猜你喜欢
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多