1. 程式人生 > >表達式計算模板(+-*/^)

表達式計算模板(+-*/^)

bre 表達 != pen main logs scan n) ==

#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; }

表達式計算模板(+-*/^)