首页 > 解决方案 > 程序仅运行 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 的任何建议?任何帮助都会得到帮助

标签: c++visual-studio

解决方案


尝试用运算符 || 替换 if 语句中的“或”。

IE。if (Calculation == "Add" || Calculation == "add") {...

http://www.cplusplus.com/doc/tutorial/operators/


推荐阅读