|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<cmath>
#include<ctype.h>
#include<malloc.h>
#include<iomanip>
using namespace std;
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
#define MAXBUFFER 10
typedef double Elemtype;
struct sqStack
{
Elemtype *base;
Elemtype *top;
int stackSize;
};
void initStack(sqStack *s)
{
s->base = (Elemtype *)malloc(STACK_INIT_SIZE *sizeof(Elemtype));
if(!s->base){
exit(0);
}
s->top = s->base;
s->stackSize = 20;
}
void Push(sqStack *s, Elemtype e)
{
if( s->top - s->base >= s->stackSize){
s->base = (Elemtype*)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(Elemtype));
if(!s->base){
exit(0);
}
}
*(s->top) = e;
s->top++;
}
void Pop(sqStack *s, Elemtype *e){
if(s->top == s->base){
return;
}
*e = *--(s->top);
}
int StackLen(sqStack s){
return (s.top - s.base);
}
int main()
{
sqStack s;
char c;
double d, e, f;
char str[MAXBUFFER];
int cnt = 0;
initStack(&s);
cout<<"请按逆波兰表达式输入带计算数据,数据与运算符之间用空格隔开,以#作为结束标志"<<endl;
cin>>c;
while(c != '#'){
while(isdigit(c) || c =='.') //用于过滤数字
{
str[cnt++] = c;
str[cnt] = '\0';
if(cnt > MAXBUFFER)
{
cout<<"出错:输入的单个数量不超过10"<<endl;
return -1;
}
cin>>c;
if( c == ' ')
{
f = atof(str);
Push(&s, f);
cnt = 0;
break;
}
}
switch( c )
{
case '+':
{
Pop(&s, &e);
Pop(&s, &d);
Push(&s, d + e);
break;
}
case '-':
{
Pop(&s, &e);
Pop(&s, &d);
Push(&s, d - e);
break;
}
case '*':
{
Pop(&s, &e);
Pop(&s, &d);
Push(&s, d * e);
break;
}
case '/':
{
Pop(&s, &e);
Pop(&s, &d);
if(e != 0)
{
Push(&s, d/e);
}
else
{
cout<<"出错了,分母为0!"<<endl;
return -1;
}
break;
}
}
cin>>c;
}
Pop(&s, &d);
cout<<"最后的结果为"<<setiosflags(ios::fixed)<<setprecision(4)<<d<<endl;
return 0;
}
|
|