题目描述:
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入:
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出:
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入:
1 + 2
4 + 2 * 5 - 7 / 11
0
样例输出:
3.00
13.36
思路:
这个是利用堆栈求表达式运算值,是数据结构中经常出现的一种算法题。
我们可以建两个栈,一个用来保存运算符,一个用来保存数字;在输入串的两边加上一个最低优先级的运算符。
从左到右遍历输入串,如果是数字,就压入到数字栈中,如果是运算符,就要和运算符栈顶的运算符进行比较,如果是小于,那么继续进栈,如果是大于,那么就将数字栈的顶的两个数字弹出,与当前的运算符进行运算,得出结果再压入到数字堆栈中。
代码如下:
#include<stdio.h>
#include<stack>
using namespace std;
int isdigit(char a)
{
if(a=='0'||a=='1'||a=='2'||a=='3'||a=='4'||a=='5'
||a=='6'||a=='7'||a=='8'||a=='9')
return 1;
else return 0;
}
int isoperator(char a)
{
if(a=='+'||a=='-'||a=='*'||a=='/'||a=='^')
return 1;
else return 0;
}
int changeOperToNum(char a)
{
if(a=='^') return 10;
if(a=='+') return 11;
if(a=='-') return 12;
if(a=='*') return 13;
if(a=='/') return 14;
}
double compute(double a, double b,int c)
{
if(c==11) return b+a;
if(c==12) return b-a;
if(c==13) return b*a;
if(c==14) return b/a;
}
int main()
{
char s[201];
int i;
int m,n;
int c;
double a,b,d;
double k;
double count;
while(gets(s))
{
if(s[0]!='0'&& s[1]!=0)
{
for(i=0; ; i++)
{
if(s[i]=='\0')
{
s[i]='^';
s[i+1]='\0';
break;
}
}
//puts(s);
stack<int> oper; // 10,11,12,13,14=^,+,-,*,/ 操作符栈
stack<double> num; // 数字栈
oper.push(10);
//操作符栈先压入^
for(i=0; s[i]!='\0'; i++)
{
count=0.0;
while(isdigit(s[i]))
{
k = s[i]-'0';
count=count*10+k;
printf("%f\n",count);
i++;
}
num.push(count);
if(isoperator(s[i]))
{
n = changeOperToNum(s[i]);
printf("%d\n",n);
m = oper.top();
printf("%d\n", m);
if(m<=n) oper.push(n);
else //执行弹出运算符和数字操作,运算之后再把数字放回栈中
{
while(m>n)
{
a = num.top();
num.pop();
printf("%f\n",a);
printf("%f\n",num.top());
b = num.top();
printf("%f\n",b);
num.pop();
c = oper.top();
oper.pop();
d = compute(a,b,c);
num.push(d);
m = oper.top();
}
oper.push(n);
}
}
}
printf("%.2f\n", num.top());
}
else break;
}
return 0;
}
注:这个代码我写了两个半小时。。。的确是很low了。不过我只看了这个题的思路,然后按照自己的理解进行了实现,这里面有许多的坑(对于我来说)。比如说输入的数字,不一定是0到9,如果是大于10的如何进行计算;要注意数据的类型,因为c++中的除法整数除是去整的。还有最低优先符怎么添加,等等这些。
感觉自己能写出来不容易,毕竟代码能力还需要提高。