|
用栈写的计算机,拿出来分享
[mw_shl_code=c,true]#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
浮点结果+括号的计算机
作者:大路
*/
typedef struct stack
{
float data[128];
int top;
}Stack;
typedef struct stack2
{
char data[128];
int top;
}Stack2;
int Vni(char op)
{
switch (op)
{
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '(':
return 0;
case ')':
return 0;
}
}
Stack* InitStack(void)
{
Stack* p1;
p1=malloc(sizeof(Stack));
p1->top=-1;
return p1;
}
Stack2* InitStack2(void)
{
Stack2* p2;
p2=malloc(sizeof(Stack2));
p2->top=-1;
return p2;
}
float Calculate(float a,char op,float b)
{
switch (op)
{
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
}
}
float PopStack(Stack *p1)
{
float c;
c=p1->data[p1->top--];
return c;
}
void PushStack(Stack *p1,float a)
{
p1->data[++p1->top]=a;
}
char PopStackCh(Stack2 *p2)
{
char c;
c=p2->data[p2->top--];
return c;
}
void PushStackCh(char ss,Stack* p1,Stack2* p2)
{
char fuhao;
float a,b;
float answer;
if (p2->top!=-1)
{
if (Vni(ss)<=Vni(p2->data[p2->top]))
{
if (ss==')')
{
while(p2->data[p2->top]!='(')
{
fuhao=PopStackCh(p2);
b=PopStack(p1);
a=PopStack(p1);
answer=Calculate(a,fuhao,b);
PushStack(p1,answer);
}
p2->top=p2->top-1;
}
else if (ss=='(')
{
p2->data[++p2->top]=ss;
}
else
{
fuhao=PopStackCh(p2);
b=PopStack(p1);
a=PopStack(p1);
printf("计算了 %3.3f %c %3.3f\n",a,fuhao,b);
answer=Calculate(a,fuhao,b);
PushStack(p1,answer);
p2->data[++p2->top]=ss;
}
}
else
{
p2->data[++p2->top]=ss;
}
}
else
{
p2->data[++p2->top]=ss;
}
}
void jisuan(char *s,Stack *p1,Stack2 *p2)
{
int i=0;
float sum=0;
float t=1;
while(s!='\0')
{
if (s>='0'&&s<='9')
{
do
{
sum=(float)(s-'0')+sum*10;
i++;
if (s=='.')
{
do
{
i++;
t=0.1*t;
sum+=(float)(s-'0')*t;
}while(s>='0'&&s<='9');
t=1;
}
}
while(s>='0'&&s<='9');
PushStack(p1,sum);
sum=0;
if (s=='\0')
{
break;
}
}
if (s=='+'||'-'||'*'||'/'||'('||')')
{
PushStackCh(s,p1,p2);
}
else
{
printf("input error hahahaha\n");
}
i++;
}
}
int main()
{
float a,b;
char fuhao;
char s[120];
float answer;
gets(s);
Stack *p1;
Stack2 *p2;
p1=InitStack();
p2=InitStack2();
jisuan(s,p1,p2);
while(p2->top!=-1)
{
fuhao=PopStackCh(p2);
b=PopStack(p1);
a=PopStack(p1);
answer=Calculate(a,fuhao,b);
PushStack(p1,answer);
}
printf("anwer is %3.3f\n",answer);
return 0;
}
[/mw_shl_code] |
|