Ternary Calculation
Description
Complete the ternary calculation.
Input
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 "number1operatoranumber2operatorbnumber3". Each operator will be one of {'+', '-' , '*', '/', '%'}, and each number will be an integer in [1, 1000].
Output
For each test case, output the answer.
Sample Input
5 1 + 2 * 3 1 - 8 / 3 1 + 2 - 3 7 * 8 / 5 5 - 8 % 3
Sample Output
7 -1 0 11 3
Note
The calculation "A % B" means taking the remainder of A divided by B, and "A / B" means taking the quotient.
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; char alp[] = { '+', '-' , '*', '/', '%' }; int judge(int a, char x, int b) { switch (x) { case '+': return a + b; break; case '-': return a - b; break; case '*': return a * b; break; case '/': return a / b; break; case '%': return a % b; break; } } int main(){ int t, a, b, c; char al1, al2; cin >> t; while (t--) { int result = 0; scanf("%d %c %d %c %d", &a, &al1, &b, &al2, &c); if (al1 == alp[2] || al1 == alp[3] || al1 == alp[4]) { result = judge(a, al1, b); result = judge(result, al2, c); }
//之前没有考虑到这种情况,然后wa了 else if ((al1 == alp[0] || al1 == alp[1]) && (al2 == alp[0] || al2 == alp[1])) { result = judge(a, al1, b); result = judge(result, al2, c); } else { result = judge(b, al2, c); result = judge(a, al1, result); } cout << result << endl; } return 0; }