一:简述题意
有一个式子 里面有两种符号:+ -,以及一些数字。求这个式子的值.
二:算法分析
显然,这是个中缀表达式求值的模版题。
于是,我们想到用栈来做这道题。
三:参考代码
python整活:
print(eval(input()))c++正解:
#include <bits/stdc++.h>
using namespace std;
#define MAXSIZE 101 //数组大小
int symcmp(char a, char b)
{
if (b == '(')
return 1;
else if ((b == '*' || b == '/') && (a == '+' || a == '-' || a == '('))
return 1;
else if ((b == '+' || b == '-') && (a == '('))
return 1;
else
return 0;
}
int calculate(char c,int a,int b)
{
int tmp = 0;
switch (c)
{
case '+':tmp = b + a; break;
case '-':tmp = b - a; break;
}
return tmp;
}
int calculate_expression(string str)
{
int num_stack[MAXSIZE];
int num_top = -1;
char sym_stack[MAXSIZE];
int sym_top = -1;
int i = 0;
while (str[i] != '\0')
{
if (isdigit(str[i]))
{
int val = 0;
while (isdigit(str[i]))
{
val = val * 10 + str[i] - '0';
i++;
}
num_stack[++num_top] = val;
}
else
{
if (str[i] == ')')
{
while (sym_stack[sym_top] != '(')
{
int ret = calculate(sym_stack[sym_top], num_stack[num_top], num_stack[num_top - 1]);
sym_top--;
num_top -= 2;
num_stack[++num_top] = ret;
}
sym_top--;
i++;
}
else if (!symcmp(sym_stack[sym_top], str[i]))
{
while (sym_top > -1 && (!symcmp(sym_stack[sym_top], str[i])))
{
int ret = calculate(sym_stack[sym_top], num_stack[num_top], num_stack[num_top - 1]);
sym_top--;
num_top -= 2;
num_stack[++num_top] = ret;
}
sym_stack[++sym_top] = str[i];
i++;
}
else
{
sym_stack[++sym_top] = str[i];
i++;
}
}
}
while (sym_top > -1)
{
int ret = calculate(sym_stack[sym_top], num_stack[num_top], num_stack[num_top - 1]);
sym_top--;
num_top -= 2;
num_stack[++num_top] = ret;
}
return num_stack[0];
}
int main()
{
#ifdef TigerDuan //防抄袭
string str;
cin>>str;
int ret = calculate_expression(str); //计算
printf("%d\n", ret);
return 0;
}