如果是其他位置

时间:2014-08-27 01:56:45

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

我正在尝试用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不为零,则给出答案。

2 个答案:

答案 0 :(得分:4)

问题是您的最后cout应位于else区块内:

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

正如所写,您的"quotient is: " << quot正在执行,但实际上您只希望在b == 0评估为false时执行。

答案 1 :(得分:1)

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