马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#define STACK_INIT_SIZE 20
#define STACKINCREAMENT 10
#define MAXBUFFER 10
typedef double ElementType;
typedef struct {
ElementType* base;
ElementType* top;
int stackSize;
}sqStack;
void InitStack(sqStack* s);
bool StackEmpty(sqStack* s);
void Push(sqStack* s, double e);
void Pop(sqStack* s, double* e);
int main()
{
sqStack* s = (sqStack*)malloc(sizeof(sqStack*));
InitStack(s);
char buffer[MAXBUFFER];
char c = '0';
double left, right, result;
printf("Please input a string of RPN expression, the # character ends up with the input\n");
while (true) {
int i = 0;
while (1) {
scanf("%c", &c);
if (isdigit(c)||c == '.') {
buffer[i++] = c;
}
else if(c == ' ' && i != 0){
buffer[i] = '\0';
double value = atof(buffer);
Push(s, value);
break;
}
else {
break;
}
}
switch (c) {
case '+':
Pop(s, &left);
Pop(s, &right);
Push(s, left+right);
break;
case '-':
Pop(s, &right);
Pop(s, &left);
Push(s, left - right);
break;
case '*':
Pop(s, &right);
Pop(s, &left);
Push(s, left * right);
break;
case '/':
Pop(s, &right);
Pop(s, &left);
if (right == 0.0) {
printf("The divisor is not equal to zero\n");
}
Push(s, left/right);
break;
default :
break;
}
if (c == '#') {
break;
}
}
Pop(s, &result);
printf("The final result is %lf\n", result);
return 0;
}
void InitStack(sqStack* s) {
s->top = s->base = (ElementType*)malloc(STACK_INIT_SIZE * sizeof(double));
if (!s->top) {
exit(0);
}
s->stackSize = STACK_INIT_SIZE;
}
bool StackEmpty(sqStack* s) {
if (s->top == s->base) {
return true;
}
else {
return false;
}
}
void Push(sqStack* s, double e) {
if (s->top - s->base >= s->stackSize) {
s->base = (ElementType*)realloc(s->base, s->stackSize + STACKINCREAMENT);
if (!s->base) {
exit(0);
}
s->stackSize = s->stackSize + STACKINCREAMENT;
}
*(s->top) = e;
s->top++;
}
void Pop(sqStack* s, double* e) {
if (StackEmpty(s)) {
return;
}
*e = *--(s->top);
}
|