【发布时间】: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