计算前缀表达式

NO COPYING!  

NO COPYING!

NO COPYING!

//Sinhaeng Hhjian
//前缀表达式 
#include<bits/stdc++.h>
#define MAX 100
using namespace std;
struct Stack{
	double *base;
	int top;
};
void Push(Stack &s, double bt){
	s.base[++s.top] = bt;
}
int GetTop(Stack s, double &bt){
	if(!s.top)
		return 0;
	bt = s.base[s.top];
	return 1;
}
int IsSEmpty(Stack s){
	return s.top==0? 1 : 0;
}
void InitStack(Stack &s){
	s.base = (double *)malloc(MAX*(sizeof(double)));
	s.top=0;
}
void Pop(Stack &s){
	if(IsSEmpty(s))
		return ;
	s.top--;
}

double calculator(char str[]){
	Stack s;
	InitStack(s);
	int len=strlen(str), i=len-1;
	while ( i >= 0 ){
		if (str[i]==' ')
			i--;
        else if (str[i] >= '0' && str[i] <= '9') {
			Stack temp;
			InitStack(temp);
			while (i >=0 && str[i] >= '0' && str[i] <= '9'){
				Push(temp, str[i]-'0');
				i--;
			}
			int num=0;
			while(!IsSEmpty(temp)){
				double bt;
				GetTop(temp, bt);
				Pop(temp);
				num=num*10+bt;
			}
			Push(s, num);
		}
		else {
			double num1, num2, num3;
			GetTop(s, num1);Pop(s);
			GetTop(s, num2);Pop(s);
			if (str[i] == '+')
                num3 = num1 + num2;
            else if (str[i] == '-') 
                num3 = num1 - num2;
            else if (str[i] == '*') 
                num3 = num1 * num2;
            else if (str[i] == '/') 
                num3 = num1 / num2;
            Push(s, num3);
            i--;
		} 
	}
	return s.base[s.top];
}

int main(){
    char s[]="+ + + + + 1 * - 2 3 4 / 10 2 * 2 2 2 / 2 5";
    printf("前缀表达式为:%s\n", s);
	double ans=calculator(s);
	printf("计算结果:%f\n", ans);
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

hhjian6666

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

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

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

打赏作者

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

抵扣说明:

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

余额充值