定义
逆波兰表达式又叫做后缀表达式。逆波兰表示法是波兰逻辑学家J・卢卡西维兹(J・ Lukasiewicz)于1929年首先提出的一种表达式的表示方法 [1]。后来,人们就把用这种表示法写出的表达式称作“逆波兰表达式”。逆波兰表达式把运算量写在前面,把算符写在后面。
代码实现
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define beginlong 20
#define addlong 10
#define maxlong 10
typedef double elemtype;
typedef struct
{
elemtype* base;
elemtype* top;
int sqlong;
}sqstack;
void initsq(sqstack* s)
{
s->base = (elemtype*)malloc(beginlong * sizeof(elemtype));
if (s->base == NULL)
{
return;
}
s->top = s->base;
s->sqlong = beginlong;
}
void push(sqstack* s, elemtype e)
{
if (s->top - s->base == s->sqlong)
{
s->base = (elemtype*)realloc(s->base, (addlong + s->sqlong) * sizeof(elemtype));
if (s->base == NULL)
{
return;
}
}
*(s->top) = e;
s->top++;
}
void pop(sqstack* s, elemtype* e)
{
if (s->base == s->top)
{
return;
}
*e = *--(s->top);
}
int getlong(sqstack s)
{
return (s.top - s.base);
}
int main()
{
sqstack s;
char n;
double a, b;
int len;
char arr[maxlong] = { 0 };
int i = 0;
initsq(&s);
printf("请以逆波兰式的形式输入想求解的式子,数数之间和数符号之间加入空格,以#为结尾\n");
scanf("%c", &n);
while (n != '#')
{
while (isdigit(n) || n == '.')
{
arr[i] = n;
i++;
if (i > 9)
{
printf("您输入的值太大\n");
return -1;
}
scanf("%c", &n);
if (n == ' ')
{
a = atof(arr);
push(&s, a);
i = 0;
break;
}
}
switch (n)
{
case '-':
pop(&s, &a);
pop(&s, &b);
push(&s, b - a);
break;
case '+':
pop(&s, &a);
pop(&s, &b);
push(&s, b + a);
break;
case '*':
pop(&s, &a);
pop(&s, &b);
push(&s, b * a);
break;
case '/':
pop(&s, &a);
pop(&s, &b);
if (b != 0)
{
push(&s, b / a);
break;
}
else
{
return -1;
}
}
scanf("%c", &n);
}
pop(&s, &a);
printf("%f", a);
return 0;
}