码迷,mamicode.com
首页 > 其他好文 > 详细

表达式计算模板(+-*/^)

时间:2017-10-14 18:43:52      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:clu   turn   color   log   oda   while   stream   +=   print   

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int number[101],i=0,p=1;
char symbol[101],s[256],t[256];
void push(){symbol[++p]=s[i];}
int Pow(int a,int b){
    int res=1;
    while(b){
        if(b&1)res=res*a;
        a=a*a;
        b>>=1;
    }
    return res;
}
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;
        case‘^‘:number[p]=Pow(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;
    if(s[i]==‘^‘&&symbol[p]==‘^‘)return 1;
    return 0;
}
int main(){
    //scanf("%s",s);
    freopen("Soda.txt","r",stdin);
    gets(s);
    s[strlen(s)]=‘)‘;symbol[p]=‘(‘;
    while(i<strlen(s)){
        while(s[i]==‘ ‘)i++;
        while(s[i]==‘(‘){
            push();i++;
            while(s[i]==‘ ‘)i++;
        }
        int x=0;
        while(s[i]>=‘0‘&&s[i]<=‘9‘){
            x=x*10+s[i]-‘0‘;
            i++;
            while(s[i]==‘ ‘)i++;
        }
        number[p]=x;
        int j=0;
        do{
            if(s[i]==‘)‘){
                while(symbol[p]!=‘(‘)pop();
                number[--p]=number[p+1];
            }
            else{
                while(can())pop();
                push();
            }
            j=0;
            i++;j++;
            while(s[i]==‘ ‘)i++,j++;
        }while(i<strlen(s)&&s[i-j]==‘)‘);
    }
    printf("%d",number[0]);
    return 0;
}

 

表达式计算模板(+-*/^)

标签:clu   turn   color   log   oda   while   stream   +=   print   

原文地址:http://www.cnblogs.com/thmyl/p/7667642.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!