小甲鱼的逆波兰程序,我也看不懂,并且在VS上面有bug,以后学完一遍再回来看看
//实现对逆波兰输入的表达式的计算
//支持带小数点的数据
// a+(b-c)------>>>a b c - +
//a+(b-d)*d------>>-> a b c - d * +
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include <ctype.h>
#define Stack_Init_Size 20
#define StackInsert 10
#define MaxBuffer 10
typedef bool status;
typedef double ElemType;
typedef struct
{
ElemType* base;
ElemType* top;
int StackSize;
}SqStack;
void Initial(SqStack* s)
{
if (!s->base)
{
exit(0);
}
s->base = (ElemType*)malloc(Stack_Init_Size * sizeof(ElemType));
s->top = s->base;
s->StackSize = Stack_Init_Size;
}
void push(SqStack* s, ElemType e)
{
if (s->top - s->base >= s->StackSize)
{
s->base = (ElemType*)realloc(s->base, (s->StackSize + StackInsert) * sizeof(ElemType));
if (!s->base)
{
exit(0);
}
s->top = s->base + s->StackSize;
s->StackSize = s->StackSize + StackInsert;
}
*(s->top) = e;
s->top++;
}
void pop(SqStack* s, ElemType* e)
{
if (!s->base)
{
exit(0);
}
s->top = s->top - 1;
*e = *(s->top);
}
int StackLen(SqStack s)
{
return (s.top - s.base);
}
int main()
{
SqStack s;
char c;
double d, e;
char str(MaxBuffer);
int *i = 0;
//
Initial(&s);
printf("请按逆波兰表达式输入待计算数据,数据与运算符用空格隔开,以#作为结束标志\n");
scanf_s("%c", &c);
while (c != '#')
{
while (isdigit(c) || c == '.')
{
str[i++] = c;
str[i] = '0';
if (*i >= 10)
{
printf("出错:输入的单个数据过大\n");
return -1;
}
scanf_s("%c", &c);
if (c == ' ')
{
d = atof(str);
push(&s, d);
*i = 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 {
printf("\n出错,分母为0\n");
return -1;
}
break;
}
scanf_s("%d,&c");
}
pop(&s, &d);
printf("\n最终的计算机结果为 %f\n", d);
//
return 0;
}