【数据结构】前缀表达式求值 · 中缀转后缀 · 后缀表达式求值

“ Ctrl AC!一起 AC!”

前缀表达式求值:

#include<bits/stdc++.h>
using namespace std;
char s[100];
double scan(){
	cin>>s;
	if(s[0]>='0'&&s[0]<='9'){
		return atof(s);
	}
	else{
		if(s[0]=='+') return scan()+scan();
		else if(s[0]=='-') return scan()-scan();
		else if(s[0]=='*') return scan()*scan();
		else return scan()/scan();
	}
}
int main(){
	printf("%f",scan());
	return 0;
}

中缀转后缀:

int is_operation(char op){
	switch(op){
		case '+':
		case '-':
		case '*':
		case '/': return 1;
		default: return 0;
	}
}
int priority(char op){
	switch(op){
		case '#': return -1;
		case '(': return 0;
		case '+':
		case '-': return 1;
		case '*':
		case '/': return 2;
		default : return -1;
	}
} 
void postfix(char e[],char f[]){ //将中缀表达式e转换成后缀表达式f
	char opst[100];int top=0;
	opst[top]='#';top++;
	int i=0,j=0;
	while(e[i]!='#'){
		if((e[i]>='0'&&e[i]<='9')||e[i]=='.') f[j++]=e[i];
		else if(e[i]=='('){
			opst[top]=e[i];top++;
		}
		else if(e[i]==')'){
			t=top-1;
			while(opst[t]!='(') {
				f[j++]=opst[--top];t=top-1;
			}
			top--;
		}
		else if(is_operation(e[i])){
			f[j++]=' '; //用空格分开两个操作数
			while(priority(opst[top-1])>=priority(e[i])) f[j++]=opst[--top];
			opst[top]=e[i];top++;
		}
		++i;
	}
	while(top) f[j++]=opst[--top];
}

后缀表达式求值:

double readnumber(char f[],int *i){ //将字符字符串转变成数
	double x=0.0;
	int k=0;
	while(f[*i]>='0'&&f[*i]<='9'){
		x=x*10+(f[*i]-'0');
		(*i)++;
	}
	if(f[*i]=='.'){
		(*i)++;
		while(f[*i]>='0'&&f[*i]<='9'){
			x=x*10+(f[*i]-'0');
			(*i)++;
			k++; //记录小数点后面有几位
		}
	}
	while(k!=0){
		x=x/10.0;
		k--;
	}
	return x;
}
double evalpost(char f[]){
	double obst[100]; //实时操作数操作记录
	int top=0;
	int i=0;
	double x1,x2;
	while(f[i]!='#'){
		if(f[i]>='0'&&f[i]<='9'){
			obst[top]=readnumber(f,&i);
			top++;
		}
		else if(f[i]==' ') i++;
		else if(f[i]=='+'){
			x2=obst[--top];
			x1=obst[--top];
			obst[top]=x1+x2;
			top++;
			i++;
		}
		else if(f[i]=='-'){
			x2=obst[--top];
			x1=obst[--top];
			obst[top]=x1-x2;
			top++;
			i++;
		}
		else if(f[i]=='*'){
			x2=obst[--top];
			x1=obst[--top];
			obst[top]=x1*x2;
			top++;
			i++;
		}
		else if(f[i]=='/'){
			x2=obst[--top];
			x1=obst[--top];
			obst[top]=x1/x2;
			top++;
			i++;
		}
	}
	return obst[0];
}

感谢阅读!!!

“ Ctrl AC!一起 AC!”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ctrl AC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值