我想学习一些C++,并且我决定构建一个基本的I/O计算器。它正确运行,直到第二个getUserInput(),然后它自动输入0并终止。我无法弄清楚发生了什么!C++新手 - 基本计算器问题
#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));
}
您的操作员应该存储在'char'中。输入整数的符号不太好。 – chris 2012-08-17 16:25:30
您需要检查用户是否输入了整数。请参阅http://web.eecs.utk.edu/~cs102/lectures/cinLecture.html – 2012-08-17 16:25:50
您绝对不能在布尔上下文外使用'cin >>'。永远。在解决问题之前,甚至不要进一步观察。 – 2012-08-17 16:26:30