Complete the ternary calculation.
There are multiple test cases. The first line of input contains an integer T indicating the number of test cases. For each test case:
There is a string in the form of "number1 operatora number2 operatorb number3". Each operator will be one of {'+', '-' , '*', '/', '%'}, and each number will be an integer in [1, 1000].
For each test case, output the answer.
5 1 + 2 * 3 1 - 8 / 3 1 + 2 - 3 7 * 8 / 5 5 - 8 % 3
7 -1 0 11 3
The calculation "A % B" means taking the remainder of A divided by B, and "A / B" means taking the quotient.
題目的大致意思就是:
給你3個實型整數,然後兩個運算符,要你模擬它的過程,然後得出最終的答案。
一開始我想的是分別把這幾個運算符存到數組中去,然後判斷第幾個再進行相應的過程,但是後來發現這樣會有錯誤而且寫的很復雜,因為你並沒有判斷過符號的優先順序,所以最後算出來的結果可能是錯的。
後來我瞄了一下題解,發現可以用暴力枚舉法,因為數據量不是很大,所以直接分類就好。
1.oper1是低級的運算符(即為+或是-),oper2是高級的運算符(即為*、/、%),那麼就先算第二個然後再算第一個;
2.oper1是低級的,oper2也是低級的,那麼直接順序相加就好。
3.oper1是高級的,oper2是高級的或是低級的,那麼也是直接順序的算過來就好。
#include#include int main(){ int a,b,c,T,i,j,k,sum; char ss1[10],ss2[10]; scanf("%d",&T); while(T--){ scanf("%d%s%d%s%d",&a,ss1,&b,ss2,&c); sum=0; //注意這裡不能直接把ss2[0]=='+'或'-'給寫進去,因為這樣的話還是從第二個開始計算,然後才算第一個的, //比如樣例1-3+2這樣的就錯了; if((ss1[0]=='+'||ss1[0]=='-')&&(ss2[0]=='*'||ss2[0]=='/'||ss2[0]=='%')){ if(ss2[0]=='*') sum=b*c; else if(ss2[0]=='/') sum=b/c; else if(ss2[0]=='%') sum=b%c; else if(ss2[0]=='+') sum=b+c; else if(ss2[0]=='-') sum=b-c; if(ss1[0]=='+') sum+=a; else if(ss1[0]=='-') sum=a-sum; } if((ss1[0]=='+'||ss1[0]=='-')&&(ss2[0]=='+'||ss2[0]=='-')){ if(ss1[0]=='+') sum=a+b; else if(ss1[0]=='-') sum=a-b; if(ss2[0]=='+') sum+=c; else sum-=c; } if((ss1[0]=='*'||ss1[0]=='/'||ss1[0]=='%')&&(ss2[0]=='*'||ss2[0]=='/'||ss2[0]=='%'||ss2[0]=='+'||ss2[0]=='-')){ if(ss1[0]=='*') sum=a*b; else if(ss1[0]=='/') sum=a/b; else if(ss1[0]=='%') sum=a%b; if(ss2[0]=='*') sum=sum*c; else if(ss2[0]=='/') sum=sum/c; else if(ss2[0]=='%') sum=sum%c; else if(ss2[0]=='+') sum+=c; else if(ss2[0]=='-') sum-=c; } printf("%d\n",sum); } }