当前位置: 代码迷 >> 综合 >> 中缀表达式转后缀并计算值
  详细解决方案

中缀表达式转后缀并计算值

热度:38   发布时间:2023-09-23 09:56:00.0

数字只能(0~9)运算符 加减乘除还有括号

#include<iostream>
#include<algorithm>
#include<map>
#include<stack>
#include<string>
#include<cstring>
#include<cctype>
using namespace std;
#define maxn 100
void ToLast(string s,char* ans);
double Value(char* ans);
int main()
{	string s;   while(cin>>s){char ans[maxn]={0};ToLast(s,ans);cout<<ans<<endl;cout<<Value(ans)<<endl;} 
}void ToLast(string s,char* ans)
{map<char,int> cmp;  //通过比较数字大小来比较优先级 cmp['+']=1;cmp['-']=1;cmp['*']=2;cmp['/']=2;stack<char> sk;int p=0;int len=s.length();for(int i=0;i<len;i++){if(isdigit(s[i])){ans[p++]=s[i];}else {if(s[i]=='(') {sk.push(s[i]);continue;}else if(s[i]!=')'){if(sk.empty())sk.push(s[i]);else {while(!sk.empty()&&cmp[s[i]]<=cmp[sk.top()]){ans[p++]=sk.top();sk.pop();}sk.push(s[i]);}}else{while(sk.top()!='('){ans[p++]=sk.top();sk.pop();}sk.pop();}}}while(!sk.empty()) {ans[p++]=sk.top();sk.pop();}ans[p++]='\0';
}double Value(char* ans)   //计算后缀结果 
{stack<double> s;for(int i=0;ans[i];i++){if(isdigit(ans[i])) s.push(ans[i]-'0');else{double x;double b=s.top();s.pop();double a=s.top();s.pop();switch(ans[i]){case '*': x=a*b;break;case '/': x=a/b;break;case '+': x=a+b;break;case '-': x=a-b;break;}s.push(x);}}return s.top();
}


  相关解决方案