马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
原理:
备注:
输入方式有待改进,还有就是比小甲鱼视频中多用了一个栈F
代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXSIZE 100
typedef double Elemtype;
typedef struct
{
Elemtype *base;
Elemtype *top;
int stacksize;
}SqStack;
void InitStack(SqStack **E); //初始化栈E
void PushStack(SqStack **E, Elemtype T); //进栈
Elemtype PopStack(SqStack *E); //出栈
Elemtype NumStack(SqStack *E);
Elemtype NumStack(SqStack *E) //
{
Elemtype A = 0, B = 0;
for(int i = 1; E->top != E->base; i = i * 10)
{
A = i * PopStack(E);
B += A;
}
return B;
}
Elemtype PopStack(SqStack *E) //出栈
{
E->top--;
E->stacksize++;
return *(E->top);
}
void PushStack(SqStack **E, Elemtype T) //进栈
{
if((*E)->top - (*E)->base >= (*E)->stacksize) //如果栈内空间不够
{
(*E)->base = (Elemtype *)realloc((*E)->base, ((*E)->stacksize + MAXSIZE) * sizeof(Elemtype ));
(*E)->top = (*E)->base + (*E)->stacksize;
(*E)->stacksize = (*E)->stacksize + MAXSIZE;
}
*((*E)->top) = T;
(*E)->top++;
(*E)->stacksize--;
}
void InitStack(SqStack **E) //初始化栈E
{
*E = (SqStack *)malloc(sizeof(SqStack ));
(*E)->base = (Elemtype *)malloc(MAXSIZE * sizeof(Elemtype));
(*E)->top = (*E)->base;
(*E)->stacksize = MAXSIZE;
}
int main()
{
SqStack *T, *F; //创建栈
char N[100];
Elemtype G, A, X, Z;
InitStack(&T);
InitStack(&F);
scanf("%s", N); //分割符我用的是@一开始想用数组输入
for(int i = 0; N[i] != '#'; i++)
{
if((N[i] >= '0' && N[i] <= '9') || N[i] == '.')
{
while(N[i] >= '0' && N[i] <= '9')
{
PushStack(&F, N[i] - '0');
i++;
}
G = NumStack(F);
if(N[i] == '.')
{
i++;
for(int j = 10; N[i] >= '0' && N[i] <= '9'; j = j*10)
{
A = N[i] - '0';
G += A / j;
//G += ( N[i] - '0') / j;
i++;
}
}
PushStack(&T, G);
}
switch(N[i])
{
case '+':{
Z = PopStack(T);
X = PopStack(T);
PushStack(&T, X + Z); //这里和出栈要调换顺许不然会出现错误
}
break;
case '-':{
Z = PopStack(T);
X = PopStack(T);
PushStack(&T, X - Z);
}
break;
case '*':{
Z = PopStack(T);
X = PopStack(T);
PushStack(&T, X * Z);
}
break;
case '/':{
Z = PopStack(T);
X = PopStack(T);
if(Z != 0)
{
PushStack(&T, X / Z);
}
else
{
printf("除数为0根据出发原理出发被除数不能为0\n");
}
}
break;
default:{
break;
}
}
}
printf("%f", PopStack(T));
return 0;
}
|