数据结构的练习:表达式求值
#include <iostream>
#include <string>
using namespace std;
const int Maxx = 100;
typedef struct
{
char data[Maxx];
}operators;
typedef struct
{
float data[Maxx];
}numbers;
numbers nums;
operators opers;
char cspS[7] = {'#', ')', '+', '0', '*', '0', '('};
char ispS[7] = { '#', '(', '0', '+', '0', '*', ')' };
char trans(char s){
if (s == '/'){
return '*';
}
else if (s == '-'){
return '+';
}
else{
return s;
}
}
int comPri(char operS,char operC){
int numC,numS;
for (int i = 0; i < 7; ++i)
{
if (ispS[i]==operS)
numS=i;
if (cspS[i]==operC)
numC=i;
}
if(numC>numS)
return 1;
else if (numC==numS)
return 0;
else
return -1;
}
float cal(char oper,float num1,float num2){
if (oper == '+'){
return num1 + num2;
}else if(oper=='-')
return num1-num2;
else if(oper=='*')
return num1*num2;
else if (oper == '/')
return num1 / num2;
else
return 0;
}
int main()
{
char ch;
int numTop=-1,operTop=-1;
opers.data[++operTop]='#';
ch = getchar();
while(ch!='#'||operTop>0){
if (ch >= 48 && ch <= 57){
float temNum=(float)((int)ch % 48);
while ((ch = getchar())>=48&&ch<=57){
temNum = temNum * 10 + (float)((int)ch % 48);
}
nums.data[++numTop] = temNum;
}else{
char tem=trans(ch);
int res=comPri(trans(opers.data[operTop]),tem);
if (res>0)
{
opers.data[++operTop]=ch;
ch = getchar();
}else if(res<0)
{
nums.data[numTop-1] = cal(opers.data[operTop], nums.data[numTop - 1], nums.data[numTop]);
numTop--;
operTop--;
}else {
operTop--;
ch = getchar();
}
}
}
cout<<nums.data[numTop]<<endl;
getchar();
getchar();
return 0;
}
运用进栈和出栈