有兄嘚知道这个逆波兰代码出错在哪吗?输出始终为0
#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;
int cnt = 0;
initStack(&s);
cout<<"请按逆波兰表达式输入带计算数据,数据与运算符之间用空格隔开,以#作为结束标志"<<endl;
cin>>c;
while(c != '#'){
while(isdigit(c) || c =='.') //用于过滤数字
{
str = c;
str = '\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;
}
嘿嘿,我找到了问题的地方:读不了空格 兄弟,我也遇到了这问题,不知道你怎么解决的
页:
[1]