算术表达式

    此算术运算是利用栈具体实现,并且是整数运算:
#include<stdio.h>
#include<stack>
#define Inf 0xfffffff
using namespace std;

stack<int> p;
stack<char> q;


int num1,num2,num;
int Caculate(char s){//具体执行运算
switch(s){
case '+':num=num1+num2;break;
case '-':num=num1-num2;break;
case '*':num=num1*num2;break;
case '/':if(num2==0)
num=Inf;
else
num=num1/num2;break;
}
return num;
}
int JudgeAddD(char s){//当第二个字符(+,-)来时判断第一个时候能进行运算
    char ch=q.top();
    q.pop();
if(ch!='#' && ch!='('){
         num2=p.top();
p.pop();
num1=p.top();
p.pop();
num2=Caculate(ch);
if(num2!=Inf){
             p.push(num2);
return 1;
}
}
q.push(ch);
return 0;
}

int JudgeMulD(){//当第二个字符(*,/)来时判断第一个时候能进行运算
char ch=q.top();
q.pop();
if(ch=='*' || ch=='/'){
num2=p.top();
p.pop();
num1=p.top();
p.pop();
num2=Caculate(ch);
if(num2!=Inf){
p.push(num2);
return 1;
}
}
q.push(ch);
return 0;
}

void Judge(){//当接下来的字符是')'
char ch=q.top();
q.pop();
while(ch!='('){
num2=p.top();
p.pop();
num1=p.top();
p.pop();
num2=Caculate(ch);
if(num==Inf)
break;
p.push(num2);
ch=q.top();
q.pop();
}
}
int main(){
char ch;
int sum;
q.push('#');//
ch=getchar();
num=0;
while(ch!='\n'){
if(ch==' ')
continue;
if(num==Inf)//发现有除数为0的情况就不用再运算了
        {
            ch=getchar();
            continue;
        }
if(ch>='0' && ch<='9'){//保存数字
            sum=ch-'0';
while(1){
ch=getchar();
if(ch<'0' || ch>'9')
break;
sum*=10;
sum+=ch-'0';
}
p.push(sum);
}
else{
switch(ch){//判断运算符
case '+':
case '-':while(JudgeAddD(ch));break;
case '*':
case '/':while(JudgeMulD());break;
case ')':Judge();break;
default:;
}
if(ch!=')')
q.push(ch);
ch=getchar();
}
}
while(num!=Inf){//做最后的清理
num2=p.top();
p.pop();
if(!p.empty()){
ch=q.top();
q.pop();
num1=p.top();
p.pop();
num2=Caculate(ch);
p.push(num2);
}
else
      break;
}
if(num==Inf)
printf("error!\n");//当有除数为0的情况
else
printf("%d\n",num2);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值