#include<cstdio>
#include<cstdlib>
#include<cstring>
int number[101],i=0, p=1;
char symbol[101],s[256], t[256];
void push(){
symbol[++p]=s[i];
}
void pop(){
switch (symbol[p--]){
case '+':number[p]+=number[p + 1];break;
case '-':number[p]-=number[p + 1];break;
case '*':number[p]*=number[p + 1];break;
case '/':number[p]/=number[p + 1];break;
}
}
bool can(){
if((s[i]=='+'||s[i]=='-')&&symbol[p]!='(')
return 1;
if((s[i]=='*'||s[i]=='/')&&(symbol[p]=='*'||symbol[p]=='/'))
return 1;
return 0;
}
int main(){
printf("String :");gets(s);
s[strlen(s)]=')';symbol[p]='(';
while(i<strlen(s)){
while (s[i]=='('){
push();
i++;
}
int x=0;
while(s[i]>='0'&&s[i]<='9')
x=x*10+s[i++]-'0';
number[p]=x;
do{
if (s[i]==')'){
while(symbol[p]!='(')
pop();
number[--p]=number[p+1];
}
else{
while(can())
pop();
push();
}
i++;
}while(i<strlen(s)&&s[i-1]==')');
}
printf("Result=%d", number[0]);
return 0;
}
求算术表达式的值
最新推荐文章于 2021-12-10 01:11:55 发布