求表达式的值
下面的代码有问题,带括号的算不了,哪位大佬能帮我修复一下;我崩溃了。。。。
#include<stdio.h>
#include<stdio.h>
#include <stdlib.h>
typedef struct {
int num[100];
int top;
}Stack1;
typedef struct {
char num[100];
int top;
}Stack2;
void Init_stack1(Stack1 *s)
{
s->top=0;
}
void Init_stack2(Stack2 *s)
{
s->top=0;
}
void Push_stack1(Stack1 *s,int *e)
{
s->num[s->top]=*e;
s->top++;
}
void Push_stack2(Stack2 *s,char *e)
{
s->num[s->top]=*e;
s->top++;
}
int Pop_stack1(Stack1 *s)
{
int e;
e=s->num[--s->top];
return e;
}
char Pop_stack2(Stack2 *s)
{
char e;
e=s->num[--s->top];
return e;
}
int GetTop_stack1(Stack1 *s)
{
int e;
e=s->num[s->top-1];
return e;
}
char GetTop_stack2(Stack2 *s)
{
char e;
e=s->num[s->top-1];
return e;
}
//判断优先级
char _judge(char *a,char *b)
{
if(*a=='+'&&(*b=='+'||*b=='*'||*b=='/'||*b=='('))
{
return '<';
}
else if(*a=='-'&&(*b=='-'||*b=='*'||*b=='/'||*b=='('))
{
return '<';
}
else if(*a=='*'&&(*b=='*'||*b=='('))
{
return '<';
}
else if(*a=='/'&&(*b=='/'||*b=='('||*b=='*'))
{
return '<';
}
else if(*a=='('&&(*b=='+'||*b=='-'||*b=='*'||*b=='/'))
{
return '<';
}
else if((*a=='('&&*b==')')||(*a=='#'&&*b=='#'))
{
return '=';
}
else if (*a=='#'&&(*b=='-'||*b=='+'||*b=='/'||*b=='*'))
{
return '<';
}
else
{
return '>';
}
}
//二元运算
int calculate(int *a,int *b,char *c)
{
int num1=*a,num2=*b;
if(*c=='+')
{
return num1+num2;
}
else if(*c=='-')
{
return num1-num2;
}
else if(*c=='*')
{
return num1*num2;
}
else if(*c=='/')
{
return num1/num2;
}
else
return 0;
}
int main(){
Stack1 s1,*num;
Stack2 s2,*symbol;
num=&s1; symbol=&s2;
Init_stack1(num);
Init_stack2(symbol);
char str[30];
printf("请输入表达式\n");
scanf("%s",str);
int i=1;
Push_stack2(symbol, &str[0]);
while(str[i]!='\0')
{
if(str[i]>='0'&&str[i]<='9')
{
int t=(int)str[i]-48;
Push_stack1(num, &t);
}
else
{
char t=GetTop_stack2(symbol);
int a,b;char t1;int t2,t3;
switch (_judge(&t, &str[i])) {
case '<':
Push_stack2(symbol, &str[i]);
break;
case '=':
Pop_stack2(symbol);
break;
case '>':
if(str[i]==')')
{
t1=Pop_stack2(symbol);
a=Pop_stack1(num);
b=Pop_stack1(num);
t2=calculate(&b, &a, &t1);
Push_stack1(num,&t2);
t3=Pop_stack2(symbol);
}
else
{
t1=Pop_stack2(symbol);
a=Pop_stack1(num);
b=Pop_stack1(num);
t2=calculate(&b, &a, &t1);
Push_stack1(num,&t2);
i--;
}
break;
}
}
i++;
}
printf("%d\n",Pop_stack1(num) );
printf("%c",GetTop_stack2(symbol));
}
/* 运行结果
请输入表达式
#1-5+7+2*3#
9
Program ended with exit code: 0
*/
原文:https://www.cnblogs.com/zhulmz/p/11666340.html