c++ - 程序仅运行 if 而不是 else if/else
问题描述
我是 C++ 新手,我正在努力处理 if/else if 语句。该程序是一个计算器,可以执行基本的加法、减法、乘法和除法。用户给出 2 个数字和一个操作,该操作用作指示如何处理前两个数字输入。代码如下。
```#include <iostream>
using namespace std;
int main()
{
//Get User Inputs
int UserInput1, UserInput2, Output;
string Calculation;
cout << "Input first number ";
cin >> UserInput1;
cout << "\n\nInput Second Number ";
cin >> UserInput2;
cout << "\n\nAdd, Subtract, Multiply or Divide? ";
cin >> Calculation;
cout << "\n\n";
if (Calculation == "Add" or "add") { //Performs addition
Output = UserInput1 + UserInput2;
cout << UserInput1 << " + " << UserInput2 << " = " << Output;
} else if (Calculation == "Subtract" or "subtract") { //Performs subtraction
Output = UserInput1 - UserInput2;
cout << UserInput1 << " - " << UserInput2 << " = " << Output;
} else if (Calculation == "Multiply" or "multiply") { //Performs multiplication
Output = UserInput1 * UserInput2;
cout << UserInput1 << " * " << UserInput2 << " = " << Output;
} else if (Calculation == "Divide" or "divide") { //Performs division
Output = UserInput1 / UserInput2;
cout << UserInput1 << " / " << UserInput2 << " = " << Output;
} else {
cout << "Error";
}
}```
当程序运行时,它会按预期要求输入,但无论您输入什么,它都只会运行 if 语句。下面是输出。
Input first number 5
Input Second Number 5
Add, Subtract, Multiply or Divide? multiply
5 + 5 = 10
关于如何让程序包含 else ifs/else 的任何建议?任何帮助都会得到帮助
解决方案
尝试用运算符 || 替换 if 语句中的“或”。
IE。if (Calculation == "Add" || Calculation == "add") {...
推荐阅读
- linux - 根据输出从配置文件中解析变量
- oauth-2.0 - 没有电子邮件的 Azure AD B2C 响应?
- html - 修复子菜单以在切换或悬停时显示
- r - 从 .rmd 文件运行外部 .rmd 文件 - R
- spring-data-jpa - 在spring data jpa中将一个字段标记为一个数据源但不是另一个数据源的瞬态
- javascript - 如何根据活动选项卡的 url 更改 chrome.getCookies 中的 url 参数
- json - 仅显示 Object.keys 的第一个元素
- javascript - 是否存在强制所有外部链接和横幅广告在新窗口中打开的代码?
- javascript - Dialogflow(通过 Twilio 发送文本消息)
- javascript - 如何插入转换延迟