#include <iostream>
#include <stack>
using namespace std;
int Priority(char ch)
{
switch(ch)
{
case '(':
return 3;
case '*':
case '/':
return 2;
case '+':
case '-':
return 1;
default:
return 0;
}
}
int main()
{
char opt[100] = {0};
stack<int> stack_num; //保存操作數
stack<char> stack_opt; //保存操作符
int i = 0, tmp = 0;
char option;
int num1, num2;
cout << "Please input : " << endl;
cin >> opt;
while (opt[i] != '\0' || stack_opt.empty() != true)
{
if (opt[i] >= '0' && opt[i] <= '9') //操作數進棧
{
tmp = tmp * 10 + opt[i] - '0';
i++;
if (opt[i] < '0' || opt[i] > '9')
{
stack_num.push(tmp);
tmp = 0;
}
}
else //操作符
{
if (stack_opt.empty() || (stack_opt.top() == '(' && opt[i] != ')') ||
Priority(opt[i]) > Priority(stack_opt.top())) //操作符進棧
{
stack_opt.push(opt[i]);
i++;
continue;
}
if (stack_opt.top() == '(' && opt[i] == ')') //操作符出棧不計算
{
stack_opt.pop();
i++;
continue;
}
if ((opt[i] == '\0' && stack_opt.empty() != true) ||
opt[i] == ')' && stack_opt.top() != '(' ||
Priority(opt[i]) <= Priority(stack_opt.top())) //出棧 計算
{
option = stack_opt.top();
stack_opt.pop();
switch(option)
{
case '+':
num1 = stack_num.top();
stack_num.pop();
num2 = stack_num.top();
stack_num.pop();
stack_num.push(num1 + num2);
break;
case '-':
num1 = stack_num.top();
stack_num.pop();
num2 = stack_num.top();
stack_num.pop();
stack_num.push(num2 - num1);
break;
case '*':
num1 = stack_num.top();
stack_num.pop();
num2 = stack_num.top();
stack_num.pop();
stack_num.push(num1 * num2);
break;
case '/':
num1 = stack_num.top();
stack_num.pop();
num2 = stack_num.top();
stack_num.pop();
stack_num.push(num2 / num1);
break;
}
}
}
}
cout << "result : " << stack_num.top() << endl;
return 0;
}
後綴表達式計算(代碼)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.