找到了好几年前写的代码 C写的 支持的运算符','+','-','*','/','%,可以有括号()
#include<stdio.h>
char infix[100];
char postfix[100];
int topPostfix=-1;
typedef enum{lparen,rparen,plus,minus,times,divide,mod,oprand}precedence;
precedence stack1[100];
int topstack1=-1;
int instack1[]={0,0,12,12,13,13,13,0};
char instack1ch[]={'(',')','+','-','*','/','%'};
int stack2[100];
int top=-1;
void addToPostfix(char ch)
{
topPostfix++;
postfix[topPostfix]=ch;
}
precedence change(char a)
{
if(a=='(')
return lparen;
if(a==')')
return rparen;
if(a=='+')
return plus;
if(a=='-')
return minus;
if(a=='*')
return times;
if(a=='/')
return divide;
if(a=='%')
return mod;
}
void addToStack1(char ch)
{
precedence a,b;
b=change(ch);
if(ch==')')
{
while(stack1[topstack1]!=lparen)
{
a=stack1[topstack1];
addToPostfix(instack1ch[a]);
topstack1--;
}
topstack1--;//'('
}
else if(ch=='(')//zhijiejia
{
topstack1++;
stack1[topstack1]=b;
}
else
{
while(topstack1!=-1&&instack1[b]<=instack1[stack1[topstack1]])
{
addToPostfix(instack1ch[stack1[topstack1]]);
topstack1--;
}
topstack1++;
stack1[topstack1]=b;
}
}
void infixToPostfix()
{
int i;
for(i=0;infix[i]!='\0';i++)
if(infix[i]>='0'&&infix[i]<='9')
addToPostfix(infix[i]);
else
addToStack1(infix[i]);
while(topstack1!=-1)//
{
addToPostfix(instack1ch[stack1[topstack1]]);
topstack1--;
}
}
void outputPostfix()
{
printf("%s\n",postfix);
}
void add(int a)
{
top++;
if(top==100)
printf("full!\n");
stack2[top]=a;
}
void evalue()
{
int i;
for(i=0;postfix[i]!='\0';i++)
if(postfix[i]>='0'&&postfix[i]<='9')
add(postfix[i]-'0');
else
{
if(postfix[i]=='+')
stack2[top-1]+=stack2[top];
if(postfix[i]=='-')
stack2[top-1]-=stack2[top];
if(postfix[i]=='*')
stack2[top-1]*=stack2[top];
if(postfix[i]=='/')
stack2[top-1]/=stack2[top];
if(postfix[i]=='%')
stack2[top-1]%=stack2[top];
top--;
}
printf("%d\n",stack2[0]);
}
int main()
{
gets(infix);
infixToPostfix();
outputPostfix();
evalue();
return 0;
}
|