首先,它有助于这样
移动,if
s转换自身的功能,只是为了清楚。
bool isOperator(char c){
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
而且,不需要检查它的任何操作,只需检查输入的是一个数字:
bool isNum(char c){
return '0' <= c && c <= '9';
}
另一件事,与长链上面,你有问题如果输入字符是anyhing而不是'+'
,您还将输入tempNumber += ...
块。你将不得不检查与&&
,或者上面的功能更好:
if (isNum(userInput[iterator])){
tempNumber += userInput[iterator];
}
这也将排除任何无效的输入像b
,X
和喜欢。
然后,你的问题有双位数:
的问题是,你总是插入的tempNumber
后输入一个空格。你只需要这样做,如果数字序列完成。为了解决这个问题,只需修改你的长if-else if
链的末端:
// ... operator stuff
} else {
postfixExpression << tempNumber;
// peek if the next character is also a digit, if not insert a space
// also, if the current character is the last in the sequence, there can be no next digit
if (iterator == userInput.lenght()-1 || !isNum(userInput[iterator+1])){
postfixExpression << ' ';
}
}
这应该做的,从56 + 78 --> 56 78 +
给予正确的代表性工作。请告诉我,如果有什么问题。 :)
来源
2011-03-27 03:05:59
Xeo
不完全与您的问题有关,但无论如何:开关和if语句会导致优化后大多数编译器上的机器代码相同。但是,如果级联会遗留可能未初始化的返回值(您的编译器应该已经警告过您),您应该修复该错误(或使用switch语句是正确的)。一般来说,我会在这种情况下使用switch语句,因为我觉得它更简洁,但是这是我猜想的味道。 – ChrisWue 2011-03-27 03:26:37
@ChrisWue谢谢你的输入....你是对的,我应该返回0或其他东西,如果没有其他命中。是的,一般来说,我只是不知道switch语句是否更快,但我同意你的看法,switch语句看起来很酷哈哈 – 2011-03-27 04:03:24