学习随记十一——用顺序栈计算逆波兰表达式

用顺序栈计算逆波兰表达式

我遇到的主要问题:怎么储存表达式以及将表达式中的数字转化成基本数据类型,我看了许多博客尝试过用stringstream的方法,但是每次遇到不知名错误调试求证无果,后找到了c++自带的类型转换函数stod,真的很棒(๑•̀ㅂ•́)و✧。

学到的一些知识:后缀表达式的算法,string与基本数据类型间的转换,以及用erase函数清空string变量

后缀表达式的算法:遇到数字存入栈中,遇到操作符号弹出两个数字计算后存入栈中直到只剩最后结果

代码实现(包括我的之前的错误代码):

注:我是用空格区分数字,且操作符号间不能有空格

#include<iostream>
#include<sstream>
#include<string>
const int stacksize=100;
typedef struct Stack{
	double data[stacksize];			//数据域 
	int top=-1;						//指示栈顶位置 
}Stack;
using namespace std;
int Isempty(Stack*);				//判栈空
int Isfull(Stack*);					//判栈满
int Push(Stack*,double);			//进栈
double Pop(Stack*);					//退栈
void Input(string&);				//输入后缀表达式 
double Calculate(string);			//计算后缀表达式 
int main(void){
	string postfix;
	Input(postfix);
	double sum;
	sum=Calculate(postfix);
	cout<<sum;
	return 0;
}
int Isempty(Stack*p){
	return p->top==-1;
}
int Isfull(Stack*p){
	return p->top==stacksize-1;
}
int Push(Stack*p,double x){
	if(Isfull(p)){
		cout<<"The stack is full"<<endl;
		return 0;
	}else{
		p->data[++p->top]=x;		//data中p->top自加后对应的单元存入x 
	}
	return 1;						//函数正常调用 
}
double Pop(Stack*p){
	if(Isempty(p)){
		cout<<"The stack is empty"<<endl;
		return 0;
	}else{
		return p->data[p->top--];	//返回data[p->top]然后p->top-- 
	}
}
void Input(string& postfix){
	cout<<"请输入一个后缀表达式"<<endl;
	getline(cin,postfix);
}
double Calculate(string postfix){
	string temp;
	//stringstream tempstr;
	Stack p;
	int i;
	double temp1=0,temp2=0,temp3=0,sum;
	for(i=0;i<postfix.size();i++){
		if(isdigit(postfix[i])||postfix[i]=='.'){
			temp+=postfix[i];
		}else if(postfix[i]==' '){
			if(Isfull(&p)){
				cout<<"The stack is full"<<endl;
				break;
			}else{
//			tempstr<<temp;
//			tempstr>>temp3;
			temp3=stod(temp);
			Push(&p,temp3);
			temp.erase(0);
			//tempstr.str();
			}
		}else if(postfix[i]=='+'){
			temp1=Pop(&p);
			temp2=Pop(&p);
			sum=temp1+temp2;
			Push(&p,sum);
		}else if(postfix[i]=='-'){
			temp1=Pop(&p);
			temp2=Pop(&p);
			sum=temp2-temp1;
			Push(&p,sum);
		}else if(postfix[i]=='*'){
			temp1=Pop(&p);
			temp2=Pop(&p);
			sum=temp1*temp2;
			Push(&p,sum);
		}else if(postfix[i]=='/'){
			temp1=Pop(&p);
			temp2=Pop(&p);
			sum=temp2/temp1;
			Push(&p,sum);
		}
	}
	sum=Pop(&p);
	return sum;
}

输出示例:

请输入一个后缀表达式
1 2 3 4 5 6 7 8 9 ++++++++
45


请输入一个后缀表达式
1 2.5 3.6 4.7 8.432 57.9 +++++
78.132

请输入一个后缀表达式
3.546 7.567 4.333 *+
36.3338

请输入一个后缀表达式
78.567 3.666 8.234 1.5 77 45.345 -+++/
-0.232349
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值