gpt4 book ai didi

c++ - 如果其他位置

转载 作者:太空宇宙 更新时间:2023-11-04 16:13:22 26 4
gpt4 key购买 nike

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

最佳答案

问题是你最后cout应该在 else 里面 block :

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

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

关于c++ - 如果其他位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25517797/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com