示例按照只有一位数的数值设计,可用分隔符来处理后,广义化。
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <iostream>
#include <stack>
using namespace std;
/*
Created by HarvestWu on 2018/5/4.
*/
int op(int a, char op, int b);//运算函数 "a op b"
int com(char str[]);//后缀式计算函数
int main()
{
char str[100];
while (1)
{
gets(str);
printf("%d\n", com(str));
}
return 0;
}
/*
运算函数 "a op b"
*/
int Op(int a, char op, int b)
{
switch (op)
{
case '+':return a + b; break;
case '-':return a - b; break;
case '*':return a*b; break;
case '/':return a / b; break;
}
}
/*
后缀式计算函数
*/
int com(char str[])
{
stack<int> s;//暂存操作数
char op;//暂存操作符
int a, b;
for (int i = 0; i < strlen(str); i++)
{
if (str[i] >= '0'&&str[i] <= '9')
s.push(str[i] - '0');
else
{
op = str[i];
b = s.top();//取操作数2
s.pop();
a = s.top();//取操作数1
s.pop();
s.push(Op(a,op,b));//将当前计算结果入栈
}
}
return s.top();
}