gpt4 book ai didi

c++ - 带有嵌套 if/else 的 switch 语句在 C++ 中提供多个输出

转载 作者:行者123 更新时间:2023-12-03 06:53:37 25 4
gpt4 key购买 nike

我正在为我的第一年 C++ 类(class)编写一个非常简单的程序,我在其中使用 switch 语句根据两个数字以及它们之间使用的特殊字符来获得正确的输出(加、减、乘、除)。该程序在除法案例中使用嵌套的 if 语句来检查输入的第二个数字是否为零,如果没有使用正确的特殊字符则使用 default 语句。

问题在于,如果用户除以零,或使用不正确的符号,控制台将显示预期的错误,但也会显示结果,而这只是应该显示消息。

我明白为什么它显示两行,但我不知道有什么办法可以解决它。我不允许将 switch 语句更改为 if 语句,也不允许我使用其他函数或数组。

#include <iostream>
#include <iomanip>
#include <cstdlib>

using namespace std;

int main()
{
char operatr;

double operand1 = 0,
operand2 = 0,
result = 0;
cout << "Enter a binary expression of the form: operand operator operand ";
cin >> operand1 >> operatr >> operand2;
cout << endl << endl
<< "C.S.1428.002" << endl
<< "Lab Section: L17" << endl
<< "10/14/20" << endl << endl;

cout << fixed << setprecision(1);

switch ( operatr )
{
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
if ( operand2 == 0)
{
cout << operand1 << " " << operatr << " " << operand2 << " " << "Division by zero produces an undefined result" << endl;
break;
}
else
{
result = operand1 / operand2;
break;
}
default:
cout << operand1 << " " << operatr << " " << operand2 << " Encountered unknown operator." << endl;
break;
}

cout << operand1 << " " << operatr << " " << operand2 << " = " << result << endl;

system("PAUSE>NUL");

return 0;
}

最佳答案

一个简单的解决方案是使用 bool 标志来表示操作成功,然后将其用作打印结果的条件:

//...

bool flag = true;

switch (operatr)
{
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
if (operand2 == 0)
{
cout << operand1 << " " << operatr << " " << operand2 << " "
<< "Division by zero produces an undefined result" << endl;
flag = false;
}
else
{
result = operand1 / operand2;
}
break;
default:
cout << operand1 << " " << operatr << " " << operand2 << " Encountered unknown operator." << endl;
flag = false;
break;

}
if (flag)
cout << operand1 << " " << operatr << " " << operand2 << " = " << result << endl;

//...

你也可以使用 try block ,我怀疑这可能属于您不能做的事情类别,但值得一看以供将来引用。

或按照 @VladFeinstein in his answer 的建议如果发生错误,只需从开关返回,因为它是执行中的一个。

关于c++ - 带有嵌套 if/else 的 switch 语句在 C++ 中提供多个输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64325968/

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