编译原理实验一要求在oj上答这个题,但要求的是另外一件事...用正则表达式那种递归求逆波兰式。。。
交完oj的我想改成求逆波兰式。。。但好像我递归的顺序不太对...由于时间问题就不改了
所以下面这个只是用了递归来求一个只包含 +, -, _, _ 的非负整数计算表达式的值而已
#include<stdio.h>
#include<iostream>
using namespace std;
struct stringlocal
{
double num = 0;
char c='N';
}sl[200];
double show(int start,int end)
{
double cc=1.0;
//只有一个的情况
if(start == end)
{
cout<< sl[start].num<<" ";
return sl[start].num;
}
int center=end;
while( (sl[center].c != '+') && ( sl[center].c != '-') && (center>start) )
{
center--;
}
//全是乘除的情况
if(center == start)
{
cc=sl[start].num;
cout<<sl[start].num<<" ";
//cout<<cc<<"kaishi "<<endl;
for(int i=0;i<((end-start)/2);i++)
{
if(sl[start+i*2+1].c == '*')
{
cout<<sl[start+i*2+1].c<<" ";
cc*=sl[start+i*2+2].num;
}
if(sl[start+i*2+1].c == '/')
{
cout<<sl[start+i*2+1].c<<" ";
cc/=sl[start+i*2+2].num;
}
cout<<sl[start+i*2+2].num<<" ";
}
//cout<<cc<<endl;
return cc;
}
//加减的情况
else
{
if(sl[center].c =='+')
{
cout<<sl[center].c<<" ";
return show(start,center-1)+show(center+1,end);
//cout<<sl[center].c<<" ";
}
if(sl[center].c =='-')
{
cout<<sl[center].c<<" ";
return show(start,center-1)-show(center+1,end);
//cout<<sl[center].c<<" ";
}
}
}
int main()
{
int in=100;
char c=' ';
while(in>1)
{
in=0;c=' ';
while(c!='\n')
{
if(in%2 == 0) cin>>sl[in].num;
if(in%2 == 1) cin>>sl[in].c;
in++;
c=getchar();
}
if(!(in==1 && sl[0].num ==0))
printf("%.2f\n",show(0,in-1));
//cout<<show(0,in-1)<<endl;
}
/* for(int k=0;k<in;k++)
{
cout<<sl[k].num;
cout<<sl[k].c;
}
in=0;
*/
}
版权声明:本文为weixin_42898615原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。