C ++计算器没有像我想象的那样工作

时间:2014-06-22 18:54:16

标签: c++ operators calculator

为什么我的计算器不能正常工作? Visual Studios刚问我是否想要使用上一次成功的构建。

我无法看到用户的输入是否评估为字符串?

所以这是我的代码:

#include <iostream>

using namespace std;

int main() {

    int operation;
    int a;
    int b;

    cout << "Choose an operation:\n";
    cout << "+ = Addition\n";
    cout << "- = Subtraction\n";
    cout << "* = Multiplication\n";
    cout << "/ = Division\n";

    cin >> operation;

    if (operation == "+") {
        cout << "Enter a number! \n";
        cin >> a;

        cout << "Enter another number! \n";
        cin >> b;

        sum = a + b;
        cout << sum;
    }
    if (operation == "-") {
        cout << "Enter a number! \n";
        cin >> a;

        cout << "Enter another number! \n";
        cin >> b;

        sum = a - b;
        cout << sum;
    }
    if (operation == "*") {
        cout << "Enter a number! \n";
        cin >> a;

        cout << "Enter another number! \n";
        cin >> b;

        sum = a * b;
        cout << sum;
    }
    if (operation == "/") {
        cout << "Enter a number! \n";
        cin >> a;

        cout << "Enter another number! \n";
        cin >> b;

        sum = a / b;
        cout << sum;
    }
}

1 个答案:

答案 0 :(得分:2)

operation声明为std::string,然后比较就可以了,或者您可以将其声明为char

char operation;

并按比例进行比较

if (operation == '+'){...}