📄 表达式求值.cpp
字号:
//表达式求值问题
# include<stdio.h>
# include<string.h>
# define M 100
float num_stack[M]; //数字栈
char oper_stack[M];//运算符栈
int top=0,top2=0;
int value(char c) //判断运算符的优先级
{
switch(c)
{
case '+':return 1;
case '-':return 1;
case '*':return 2;
case '/':return 2;
case '(':return 3;
case ')':return 4;
default:return 5;
}
}
int compare(char m,char n) //比较相邻运算符的优先级
{
return value(m)-value(n);
}
int panduan(char c) //判断是运算符还是数字
{
if(c>='0'&&c<='9')
return 0;
else
return 1;
}
float QiuZhi(float a,float b,char ch) //子表达式求值
{
switch(ch)
{
case'+':return a+b;
case'-':return a-b;
case'*':return a*b;
case'/':return a/b;
default:return 0;
}
}
float power(float m,int n) //求一个数的N次方
{
float s=1;
int i;
for(i=1;i<=n;i++)
s=s*m;
return s;
}
float change(char *a,int wei) //将字符串转换成数字
{
int i;
float s=0;
// n=strlen(a);
for(i=0;i<wei;i++)
s=s+power(a[i]-48,wei-i);//发现过问题并改过
return s;
}
float operate(char *s) //表达式求值
{
float a,b,c;
char ch,*p=NULL,q[M];
while(*s!='\0') //表达式长度为外循环
{
if(panduan(*s)==1) //扫描到运算符
{
if(value(*s)==3)
oper_stack[top2++]=*s;
else if(value(*s)==4)
{
ch=oper_stack[--top2];
while(value(ch)!=3)
{
b=num_stack[--top];
a=num_stack[--top];
c=QiuZhi(a,b,ch);
num_stack[top++]=c;
ch=oper_stack[--top2];
}
}
else
{
if(top2>0) //字符栈非空
{
ch=oper_stack[top2-1];
if(compare(*s,ch)>=0) //调试中发现了问题并改过
oper_stack[top2++]=*s;
else
{
oper_stack[top2-1]=*s;
b=num_stack[--top];
a=num_stack[--top];
c=QiuZhi(a,b,ch);
num_stack[top++]=c;
}
}
else //字符栈为空
oper_stack[top2++]=*s;
}
}
else //扫描到数字
{ int wei=0;
p=q;
while(panduan(*(s+1))!=1&&(s+1)!=NULL)
{
*p=*s;
p++;
s++;
wei++;
}
*p=*s;
wei++;
c=change(q,wei);
num_stack[top++]=c;
}
s++;//继续向后读取表达式
}
ch=oper_stack[--top2];
b=num_stack[--top];
a=num_stack[--top];
c=QiuZhi(a,b,ch);
return c;
}
void main()
{
float sum; //存放表达式的结果
char s[M],*p=s;//存放输入的表达式
while(1)
{
printf("请输入您要求解的表达式:\n");
gets(s);
sum=operate(s);
printf("所要求的表达式的结果为:\n");
printf("%s=%f\n",p,sum);
//printf("\n%d\n",'2'-48);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -