스 택 으로 쓴 다 괄호 의 사 칙 연산
30777 단어 알고리즘 과 데이터 구조
전에 나의 블 로그 에 재 귀적 인 소수 사 칙 연산 을 썼 다.https://blog.csdn.net/coder_what / article / details / 82682366 데이터 구 조 를 배 운 후에 스 택 으로 정수 사 칙 연산 을 다시 썼 습 니 다. 준비:
char OPE[7] ={'+','-','*','/','(',')','#'};
char OPG[7][7]={{'>','>',',',','>','>'},
{'>','>',',',','>','>'},
{'>','>','>','>',','>','>'},
{'>','>','>','>',','>','>'},
{',',',',','=',' '},
{'>','>','>','>',' ','>','>'},
{',',',',',' ','='},};
위의 두 배열 은 모든 기호의 우선 순위 관 계 를 확정 할 수 있다.
조용히 알려 드릴 게 요. 합 리 적 으로 배열 을 활용 하면 순환 을 통 해 if 분기 의 사용 을 효과적으로 감소 할 수 있 습 니 다!!https://blog.csdn.net/coder_what / article / details / 86099579 이 안 이 곱 창 좋 은 예 입 니 다!!
두 개의 스 택 을 설정 해 야 합 니 다. 하 나 는 배열 을 저장 하 는 num [] 이 고 다른 하 나 는 기호 위 치 를 저장 하 는 ope [] 입 니 다.
그리고 아래 의 두 함 수 를 통 해 위의 배열 과 결합 하면 각 기호의 우선 순 위 를 판단 할 수 있 습 니 다 ~
int In(char ch)
{
int i;
for(i=0;i<7;i++)
if(ch==OPE[i])
return i;
if(i>=7) return -1;
}
char Precede(char ch1,char ch2) // ,
{
int i=In(ch1);
int j=In(ch2);
return OPG[i][j];
}
다음은 고소 한 소스 를 드 립 니 다!
#include
#include
char OPE[7] ={'+','-','*','/','(',')','#'};
char OPG[7][7]={{'>','>',',',','>','>'},
{'>','>',',',','>','>'},
{'>','>','>','>',','>','>'},
{'>','>','>','>',','>','>'},
{',',',',','=',' '},
{'>','>','>','>',' ','>','>'},
{',',',',',' ','='},};
char s[200];//
char ope[100];//
double num[100];//
int In(char );
char Precede(char ,char );
double Operate(double ,double ,char );
double StackIO();
int main()
{
printf("please input the number you wanna operate(ending by #):");
printf("
the answer is:%.3lf",StackIO());
return 0;
}
int In(char ch)
{
int i;
for(i=0;i<7;i++)
if(ch==OPE[i])
return i;
if(i>=7) return -1;
}
char Precede(char ch1,char ch2) // ,
{
int i=In(ch1);
int j=In(ch2);
return OPG[i][j];
}
double Operate(double x1,double x2,char op)
{
switch(op)
{
case '+': return (x1+x2); break;
case '-': return (x1-x2); break;// x2-x1?
case '*': return (x1*x2); break;
case '/': return (x1/x2); break;
}
}
double StackIO()
{
int i,top_o,top_n;//
double x,y;
i=x=y=top_o=top_n=0;
ope[top_o++]='#';
scanf("%s",s); // getchar ?
do{
//getchar();
//printf("%c %d~%2.3lf %d~%c",s[i],top_n-1,num[top_n-1],top_o-1,ope[top_o-1]);
if(s[i]>='0'&&s[i]<='9')
{
x=0;
while(s[i]>='0'&&s[i]<='9')
{
x=s[i++]-'0'+x*10;
}
num[top_n++]=x;
}
else
{
switch(Precede(ope[top_o-1],s[i]))
{
case ':
ope[top_o++]=s[i++]; //
break;
case '=':
top_o--;// -2 ,
i++;
break;
case '>':
y=Operate(num[--top_n],num[--top_n],ope[--top_o]);
//top_o--; switch top_o-1, --;
num[top_n++]=y;
break;
}
}
}while(s[i-1]!='#');
return num[top_n-1];
}
GET IT!