您的位置:首页 > 编程语言 > C语言/C++

[C++]利用逆波兰式,简单实现下加减乘除的混合运算

2016-11-13 20:08 579 查看

测试代码

此处显示之前逆波兰式求法后的增量代码!

http://blog.csdn.net/u010989191/article/details/53135563

//简单加减乘除法运算  因为数据是放在堆栈中 所以前一个操作数是opB 后一个操作数是opA
int simpleCalculate(int opA, int opB, char op) {
switch (op)
{
case '+':
return opB + opA;
case '-':
return opB - opA;
case '*':
return opB * opA;
case '/':
return opB / opA;
default:
return 0;
}
}

//计算表达式的值
int calculate(string polish) {
stack<int> values;
bool lastIsNum = false;
for (int i = 0; i < polish.length(); i++) {
char c = polish.at(i);
if (c == ' ') {
lastIsNum = false;
continue;
}
else if (c >= '0'&&c <= '9') {
if (lastIsNum) {
int last = values.top();
values.pop();
last = last * 10 + (c - '0');
values.push(last);
}
else {
values.push(c - '0');
lastIsNum = true;
}
}
else {
lastIsNum = false;
int opA = values.top();
values.pop();
int opB = values.top();
values.pop();
int calResult = simpleCalculate(opA, opB, c);
values.push(calResult);
}
}
return values.top();
}

int main()
{
string str;
cout << "请输入表达式: ";
cin >> str;
string result = reversePolish(str);
cout << result << endl;
int calResult = calculate(result);
cout << "计算结果: " << calResult << endl;
system("pause");
return 0;
}


测试结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐