本文主要是介绍数据结构的练习:表达式求值,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
数据结构的练习:表达式求值
#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;elsereturn 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;
}
运用进栈和出栈
这篇关于数据结构的练习:表达式求值的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!