![]() |
#2
lyj2010lyj2010-10-24 20:59
|

#include<stdio.h>
#include<string.h>
int rank(char c1,char c2) //判断符号的优先级
{
if(c1=='(')return -1;
if(c1==')')return 1;
if(c2=='(')return -1;
if(c2==')')return 1;
if(c1=='(' && c2==')')return 0;
if(c1=='#' && c2=='#')return 0;
if(c1=='#')return -1;
if(c2=='#')return 1;
if(c2=='/' && c1=='+' )return -1;
if(c2=='/' && c1=='-' )return -1;
if(c2=='*' && c1=='+' )return -1;
if(c2=='*' && c1=='-' )return -1;
return 1;
}
void change(char sin[],char sout[]) //将中缀表达式转换成后缀表达式
{
char op[99];
int len,i,psout=0,pop=1,j=0;
len=strlen(sin);
op[0]='#';
sin[len++]='#';
for(i=0;i<len;i++)
{
scanf("%s",&sin[i]);
if(sin[i]>='0' && sin[i]<='9')
sout[psout++]=sin[i];
else
{
while(rank(op[pop],sin[i])>0)
{
sout[psout++]=op[pop-1];
pop--;
}
if(rank(op[pop],sin[i])==0)
pop--;
if(rank(op[pop],sin[i])<0)
op[pop++]=sin[i];
}
}
sout[psout]=0;
while(sout[j])
{
j++;
printf("后缀表达式为:%s",sout[j]);
}
return;
}
double sincal(double a,double b,char c) //将运算符和操作数的运行结果返回
{
if(c=='+')return(a+b);
if(c=='-')return(a-b);
if(c=='*')return(a*b);
return(a/b);
}
double calculate(char cal[]) //计算后缀表达式
{
int i=0,len,top=0;
double inter[99],a,b;
len=strlen(cal);
for(i=0;i<len;i++)
{
if(cal[i]>'0' && cal[i]<'9')
inter[++top]=cal[i]-'0';
else
{
a=inter[top-2];
b=inter[top-1];
inter[top-2]=sincal(a,b,cal[i]);
top--;
}
}
return inter[0];
}
void main()
{
printf("输入一个表达式:");
double final;
char sin[99],sout[99];
scanf("%s",sin);
change(sin,sout);
final=calculate(sout);
printf("%f\n",final);
}
看了好久,脑袋都要坏掉了#include<string.h>
int rank(char c1,char c2) //判断符号的优先级
{
if(c1=='(')return -1;
if(c1==')')return 1;
if(c2=='(')return -1;
if(c2==')')return 1;
if(c1=='(' && c2==')')return 0;
if(c1=='#' && c2=='#')return 0;
if(c1=='#')return -1;
if(c2=='#')return 1;
if(c2=='/' && c1=='+' )return -1;
if(c2=='/' && c1=='-' )return -1;
if(c2=='*' && c1=='+' )return -1;
if(c2=='*' && c1=='-' )return -1;
return 1;
}
void change(char sin[],char sout[]) //将中缀表达式转换成后缀表达式
{
char op[99];
int len,i,psout=0,pop=1,j=0;
len=strlen(sin);
op[0]='#';
sin[len++]='#';
for(i=0;i<len;i++)
{
scanf("%s",&sin[i]);
if(sin[i]>='0' && sin[i]<='9')
sout[psout++]=sin[i];
else
{
while(rank(op[pop],sin[i])>0)
{
sout[psout++]=op[pop-1];
pop--;
}
if(rank(op[pop],sin[i])==0)
pop--;
if(rank(op[pop],sin[i])<0)
op[pop++]=sin[i];
}
}
sout[psout]=0;
while(sout[j])
{
j++;
printf("后缀表达式为:%s",sout[j]);
}
return;
}
double sincal(double a,double b,char c) //将运算符和操作数的运行结果返回
{
if(c=='+')return(a+b);
if(c=='-')return(a-b);
if(c=='*')return(a*b);
return(a/b);
}
double calculate(char cal[]) //计算后缀表达式
{
int i=0,len,top=0;
double inter[99],a,b;
len=strlen(cal);
for(i=0;i<len;i++)
{
if(cal[i]>'0' && cal[i]<'9')
inter[++top]=cal[i]-'0';
else
{
a=inter[top-2];
b=inter[top-1];
inter[top-2]=sincal(a,b,cal[i]);
top--;
}
}
return inter[0];
}
void main()
{
printf("输入一个表达式:");
double final;
char sin[99],sout[99];
scanf("%s",sin);
change(sin,sout);
final=calculate(sout);
printf("%f\n",final);
}
