C++ 新手 - 基本计算器问题

标签 c++

我正在尝试学习一些 C++,因此我决定构建一个基本的 I/O 计算器。一直正确运行到第二个getUserInput(),然后自动输入0终止。我不知道发生了什么!

#include <iostream>
using namespace std;

int getUserInput() {                                        // Get user numbers
    cout << "Enter a number: " << endl;
    int userInputNumber;
    cin >> userInputNumber;
    return userInputNumber;
}

char getUserOper() {                                        // Get user math operator
    cout << "Enter a math operator: " << endl;
    int userInputOper;
    cin >> userInputOper;
    return userInputOper;
}

int doMath(int x, char oper, int y) {                       // Does math based on provided operator
    if(oper=='+') {
        return x + y;
    }
    if(oper=='-') {
        return x - y;
    }
    if(oper=='*') {
        return x * y;
    }
    if(oper=='/') {
        return x / y;
    }
    else {
        return 0;
    }
}

void printResult(int endResult) {                           // Prints end result
    cout << endResult;
}

int main() {
    int userInputOne = getUserInput();
    char userOper = getUserOper();
    int userInputTwo = getUserInput();
    printResult(doMath(userInputOne, userOper, userInputTwo) );
}

最佳答案

当你应该在 getUserOper 中使用 char 时你却使用了 int

char getUserOper() {                                        // Get user math operator
    cout << "Enter a math operator: " << endl;
    char userInputOper;
    cin >> userInputOper;
    return userInputOper;
}

关于C++ 新手 - 基本计算器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12009533/

相关文章:

c++ - 我的函数不修改其输入

c++ - 派生类中的使用声明不会隐藏从基类派生的相同函数

c++ - C++11 std::bind 和 boost::bind 的区别

c++ - 尽管没有库依赖性,但编译 cryptopp 时 MT/MD 不匹配

c++ - 使用 sync_with_stdio 时打印顺序

c++ - 空字符串加一个整数?

c++ - 一点列移位

c++ - Boost MultiIndex Container 如何使用不同的组合键进行搜索?

c++ - 变量上的 `const constexpr` 是多余的吗?

c++ - 如何在 C++ 中消除 vector 的 "doubled"元素