算數四則運算的規則是1)先乘除,後加減;2)從左算到右;3)先括號內,後括號外。
由此,算式4+23-10/5的計算順序爲4+23-10/5=4+6-10/5=4+6-2=8。
給定一個以“#”作爲結束符的算式,求出算式的結果。
給出嚴蔚敏《數據結構(C語言)》中的一段算法描述以作參考:
圖1:表達式求值算法
圖2:表達式求值算法(續)
圖3:表達式求值算法(續)
輸入
以“#”結尾的表達式,運算數爲正整數。每個表達式佔一行。
輸出
輸出表達式運算的結果。
樣例輸入
4+23-10/5#
3(7-2)#
2*3/2#
樣例輸出
8
15
3
//和前面的思路也相差不大,就是結尾改變一下就好了,詳細看代碼(不懂歡迎提問
#include<bits/stdc++.h>
using namespace std;
int fun(char c)
{
if(c=='+') return 0;
else if(c=='-') return 1;
else if(c=='*') return 2;
else if(c=='/') return 3;
else return 4;
}
int judge[5][5]={{0,0,1,1,1},{0,0,1,1,1},{-1,-1,0,0,1},{-1,-1,0,0,1},{-1,-1,-1-1,0}};
int fun1(int a,int b,char c)
{
int ans=1;
if(c=='+') ans=a+b;
else if(c=='-') ans = a - b;
else if(c=='*') ans = a * b;
else if(c=='/') ans = a / b;
else
{
for(int i=1;i<=b;i++)
ans *= a;
}
return ans;
}
int dd(char s[],int x,int y)
{
char s1[100];
int m[100]={0};
int ps1=0,pm=0,i;
for(i = x;i < y;i++){
if(s[i]>='0' && s[i]<='9'){
m[pm] += s[i]-'0';
if(s[i+1]>='0' && s[i+1]<='9')
m[pm] *= 10;
else
pm++;
}
else
{
if(s[i]!='(')
while(judge[fun(s[i])][fun(s1[ps1-1])]>=0 && ps1-1>=0)
{
pm--;
m[pm-1]=fun1(m[pm-1],m[pm],s1[ps1-1]);
ps1--;
m[pm]=0;
}
}
if(s[i]<'0' || s[i]>'9'){
if(s[i]=='('){
int j;
for(j=i+1;j<y;j++)
if(s[j]==')')
break;
m[pm++]=dd(s,i+1,j);
i=j;
}
else
{
s1[ps1++]=s[i];
}
}
if(i==y-1){
for(int t=ps1-1;t>=0;t--)
m[t] = fun1(m[t],m[t+1],s1[t]);
}
}
return m[0];
}
int main()
{
char s[100];
while(cin >> s)
{
int len=strlen(s);
s[len-1]='\0';
cout << dd(s,0,len-1) << endl;
}
return 0;
}