后缀表达式求值.cpp

来自「简单的后缀表达式求值」· C++ 代码 · 共 61 行

CPP
61
字号
#include<iostream.h>
#include<stdlib.h>
#include<strstrea.h>
const stack MaxSize=50;
typedef float ElemType;
#include "stack.h"
float Compute(char *str)
{
	Stack S;
	InitStack(S);
	istrstream ins(str);
	char ch;
	float x;
	ins>>ch;
	while(ch!='@')
	{
		switch(ch) {
		case'+': x=Pop(S)+Pop(S); break;
		case'-': x=Pop(S);x=Pop(S)-x;
			break;
		case'*': x=Pop(S)*Pop(S);break;
		case'/':x=Pop(S);
			if(x!=0.0) x=Pop(S)/x;
			else
			{cerr<<"Divisor is 0!"<<endl;
			exit(1);}
			break;
		default : ins.putback(ch);
			ins>>x;
		}
		Push(S,x);
		ins>>ch;
	}
	if(!StackEmpty(S))
	{
		x=Pop(S);
		if(StackEmpty(S)) return x;
		else {
			cerr<<"expression error!"<<endl;
			exit(1);
		}
	}
	else {
		cerr<<"Stack Empty!"<<endl;
		exit(1);
	}
	return 0;
}


void main()
{
	char a[30];
	cout<<"输入一个以@为字符结束的后缀表达式"<<endl;
	cout <<"求值结果是:"<<Compute(a)<<endl;
	cin.getline(a.sizeof(a));
}



⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?