1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| #include<iostream> #include<stack> using namespace std; void fun(char str[],int n){ stack<char> ch; stack<double> number; int i=0; while(i<n){ if(str[i]>='0'&&str[i]<='9'){ double tepNum=0; while(i<n&&str[i]!=' '){ tepNum+=str[i]-'0'; tepNum*=10; i++; } tepNum/=10; i++; if(ch.empty()==0&&(ch.top()=='/'||ch.top()=='*')){ double x=number.top(); number.pop(); if(ch.top()=='/') tepNum = (x*1.0)/tepNum; else tepNum =x * tepNum; ch.pop(); } number.push(tepNum); } else{ ch.push(str[i]); i+=2; } } double sum=0; while(ch.empty()==0){ if(ch.top()=='+') sum+=number.top(); else sum-=number.top(); number.pop(); ch.pop(); } sum+=number.top(); printf("%.2lf",sum); } int main(){ char str[18]={'4',' ','+',' ','2',' ','*',' ','5',' ','-',' ','7',' ','/',' ','1','1'}; fun(str,18); return 0; }
|