/*问题描述:
输入一个只包含个位数字的简单四则运算表达式字符串,计算该表达式的值
注:
1、表达式只含 + , -, *, / 四则运算符,不含括号
2、表达式数值只包含个位整数(0 - 9),且不会出现0作为除数的情况
3、要考虑加减乘除按通常四则运算规定的计算优先级
4、除法用整数除法,即仅保留除法运算结果的整数部分。比如8 / 3 = 2。输入表达式保证无0作为除数情况发生
5、输入字符串一定是符合题意合法的表达式,其中只包括数字字符和四则运算符字符,除此之外不含其它任何字符,不会出现计算溢出情况
要求实现函数:
int calculate(int len, char *expStr)
输入:int len : 字符串长度;char* expStr : 表达式字符串;
输出:无
返回:计算结果*/
#include <iostream>
#include <cctype>
using namespace std;
int calculate(int len, char*expstr)
{
int result=0;
int *suffix = new int[len]; //表示中缀表达式
int j = 0;
int priority = -1; //记录栈顶元素的优先级,初始为-1
int table[] = { 0, 0, 2, 1, 0, 1, 0, 2 }; //表示操作符的优先级
int *stack=new int[len]; //模拟栈
int top = -1; //栈顶
//中缀表达式转换成后缀表达式
for (int i = 0; i < len; i++)
{
//如果是数字,把数字压入到中缀表达式中
if (isdigit(expstr[i]))
{
suffix[j] = expstr[i]-'0'; //不要忘记减'0'
j++;
}
//如果是操作符,把操作符压入栈中
else
{
//如果当前操作符优先级不大于栈顶元素的优先级,则先出栈到后缀表达式中再入栈
while (priority >= table[expstr[i] % 10])
{
suffix[j] = stack[top];
j++;
top--;
//出栈之后保存新的栈顶元素的优先级
if (top != -1)
priority = table[stack[top] % 10];
else
priority = -1;
}
//直到栈顶元素的优先级小于当前操作符优先级,入栈
top++;
stack[top] = expstr[i];
priority = table[stack[top] % 10];
}
}
//如果栈不为空,则把栈中的操作符都存到后缀表达式中
while (top != -1)
{
suffix[j] = stack[top];
top--;
j++;
}
//计算后缀表达式,挨个扫描后缀表达式的元素
for (int i = 0; i < j; i++)
{
switch (suffix[i])
{
case 42:
result = stack[top - 1] * stack[top];
top--;
stack[top] = result;
break;
case 43:
result = stack[top - 1] + stack[top];
top--;
stack[top] = result;
break;
case 45:
result = stack[top - 1] - stack[top];
top--;
stack[top] = result;
break;
case 47:
result = stack[top - 1] / stack[top];
top--;
stack[top] = result;
break;
default:
top++;
stack[top] = suffix[i];
break;
}
}
return result;
}
int main()
{
int len;
cin >> len;
char*expstr = new char[len];
for (int i = 0; i < len; i++)
{
cin >> expstr[i];
}
cout << calculate(len, expstr) << endl;
return 0;
}
附上cctype库中的函数,参数类型为char型。