多个'if'语句,不带'else'

Multiple 'if' statements without an 'else'

本文关键字:不带 else if 多个 语句      更新时间:2023-10-16

我必须编写的代码基本上是一个迷你银行。它要求初始金额、操作类型以及该操作的第二个运算符。

我不允许使用else,但可以使用if语句(我不明白为什么(,也不允许使用循环或数组。

这是我到目前为止的代码:

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int operand1;
int operand2;
float output;
char action;
int main()
{
cout << fixed << showpoint << setprecision(2);
cout << "Enter the initial balance [1-1000]: " << endl;
cin >> operand1;
cout << "Enter an action (D, W, I or C):" << endl;
cin >> action;
cout << "Enter the second operand:" << endl;
cin >> operand2;
if ((action != 'D' && action != 'W' && action != 'I' && action != 'C') || (operand1 > 1000 || operand1 < 1) || 
(action == 'I' && operand2 > 15 || operand2 < 1) || (action == 'C' && operand2 != 20 && operand2 != 10 && operand2 != 5) ||
(operand2 > 1000 || operand2 < 1))
{
cout << "Input out of range" << endl;
return 0;
}
if (action == 'D')
{
output = (operand1 + operand2);
cout << "The new account balance is " << output << endl;
}
if (action == 'W')
{
output = (operand1 - operand2);
if (output<0)
{
cout << "Input out of range" << endl;
return 0;
}
cout << "The new account balance is " << output << endl;
}
if (action == 'I')
{
output = ((float)operand1 + (((float)operand2 / 100) * (float)operand1));
cout << "The new account balance is " << output << endl;
}
if (action == 'C')
{
output = operand1 % operand2;
cout << operand1 / operand2 << " bills dispensed plus " << output << endl;
}
cin.get();
cin.get();
return 0;
}

在某些情况下,我会收到多个错误,而不仅仅是一个错误。例如:

输入初始余额 [1-1000]:1030 输入操作(D、W、I 或 C(:D 输入第二个操作数:40 输入超出范围

但是,无论如何,当它看到错误时,它似乎只是继续前进,我得到以下输出:

输入初始余额 [1-1000]: 1030 输入超出范围 输入操作(D、W、I 或 C(: D 输入第二个操作数: 40 新帐户余额为 1070.00

我似乎无法弄清楚如何只有一个输出,并且它只显示没有余额的错误,而不使用else语句。

使用开关(操作(:

https://en.cppreference.com/w/cpp/language/switch

在案例之后,它可以有默认值。

也有很多约定禁止其他,但不禁止elseif - 你确定elseif在你的情况下被禁止吗?

但即使允许 elseif - switch 也更好阅读,并且是一个更优雅的解决方案。

您可以通过将所有命令视为不同的情况来使用 switch。这是其他人已经说过的。

我的贡献是,您可以将第一个 if 语句(即错误情况(放在默认情况下。

在使用 switch 语句之前,您能否检查一下是否明确声明您不能使用"else if"语句。如果没有,您应该使用它。它与"其他"语句不同。

&&的优先级高于||

if (
(action != 'D' && action != 'W' && action != 'I' && action != 'C') ||
(operand1 > 1000 || operand1 < 1) ||
//  (action == 'I' && operand2 > 15 || operand2 < 1) ||
(action == 'I' && (operand2 > 15 || operand2 < 1)) ||
(action == 'C' && operand2 != 20 && operand2 != 10 && operand2 != 5) ||
(operand2 > 1000 || operand2 < 1))
{
cout << "Input out of range" << endl;
return 0;
}

为了获得更多的可追溯性,关于代码的作用,值得努力去做:

if (action != 'D' && action != 'W' && action != 'I' && action != 'C')
{
cout << "Input out of range; action " << action << endl;
return 0;
}
if (operand1 > 1000 || operand1 < 1)
{
cout << "Input out of range; 1st operand: " << operand1 << endl;
return 0;
}
...