计算表达式(前辍表达式变为后辍表达式之后,利用栈来做)

来源:互联网 发布:淘宝旺铺50块钱交不交 编辑:程序博客网 时间:2024/06/05 17:19
浮点数的,还有括号的存在;
#include<stdio.h>#include<string.h>#include<stack>#include<stdlib.h>#include <iostream>using namespace std;char a[1010];char b[1010];stack <char> s1;stack <float> s2;int i,j,n,m,t;float x,y,z;int fun(char x){switch(x){case '+' :case '-' :return 1;case '*' :case '/' :return 2;case '(' :return 0;default  :return -1;}}float js(float x,float y,char z){switch(z){case '+':return y+x;case '-':return y-x;case '*':return y*x;default :return y/x;}}int main(){int p;char c[1010];float d;printf("请输入表达式的组数:");        scanf("%d",&t);s1.push('#');while(t--){j=0;printf("请输入这种形式的表达式: a+b= \n");scanf("%s",a);m=strlen(a)-1;for(i=0;i<m;i++){if(a[i]>='0'&&a[i]<='9'||a[i]=='.') // 浮点数的处理{        memset(c,0,sizeof(c));p=0;while(a[i]>='0'&&a[i]<='9'||a[i]=='.'){b[j++]=a[i];c[p++]=a[i++];}d=atof(c);s2.push(d);i--;}else if(a[i]=='(')  s1.push(a[i]);else if(a[i]==')'){while(s1.top()!='('){b[j++]=s1.top();x=s2.top();s2.pop();y=s2.top();s2.pop();x=js(x,y,b[j-1]);s2.push(x);s1.pop();}s1.pop();}else {while(fun(s1.top())>=fun(a[i])){b[j++]=s1.top();x=s2.top();s2.pop();y=s2.top();s2.pop();x=js(x,y,b[j-1]);s2.push(x);s1.pop();}s1.push(a[i]);}}while(s1.top()!='#'){b[j++]=s1.top();x=s2.top();s2.pop();y=s2.top();s2.pop();x=js(x,y,b[j-1]);s2.push(x);s1.pop();}b[j]='=';b[j+1]='\0';printf("后辍表达式为:");puts(b);cout << a;x=js(x,y,b[j-1]);printf("%f\n",s2.top());s2.pop();} return 0;}

0 0
原创粉丝点击