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

标签 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;
    }
}

最佳答案

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

char operation;

并做比较

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

关于C++ 计算器没有像我想象的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24354598/

相关文章:

c++ - 透明 C++ 数字/Int 包装器

swift - 当使用 < 运算符时,Swift 在退出之前会遍历指定的数字

jquery - 添加 Math.ceil

c++ - 大括号封闭的初始化列表构造函数

c++ - ifstream 函数 "get"如何改变它的字符参数?

c++ - A* 搜索,网格,8 个方向,八分之一距离作为启发式,没有找到直接路径

sql - TypeORM "OR"运算符

javascript - 使用 JavaScript 从 HTML 按钮获取值

Java Swing 计算器

c++ - 通过 DEF 文件进行的 DLL 导出符号修改似乎已被修改