C - Ternary Calculation ZOJ - 3782
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 "number1 operatora number2 operatorb number3". 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 <bits/stdc++.h>
using namespace std;
char a[10000000];///存放中缀表达式
int operating(int a,int b,char c)
{
if(c=='+')
{
return a+b;
}
else if(c=='-')
{
return a-b;
}
else if(c=='*')
{
return a*b;
}
else if(c=='/')
{
return a/b;
}
else if(c=='%')
{
return a%b;
}
}
int main()
{
int t;
cin>>t;
getchar();//吃回车
while(t--)
{
gets(a);
stack<int >l;/// 存放 运算数的栈
stack<char>k;/// 存放 运算符的栈
while(l.size())///栈清空
l.pop();
while(k.size())
k.pop();
for(int i=0; a[i]; i++)
{
if(a[i]>='0' && a[i]<='9')///遇到数字直接进栈
{
int t=0;
while(a[i]>='0' && a[i]<='9')///分离多为数字
{
t=t*10+a[i++]-'0';
}
i--;
l.push(t);
}
else if(a[i]==' ');
else if(l.size()<2) k.push(a[i]);
else if(a[i]=='+' || a[i]=='-') /// '+' '- '的运算符最低直接运算栈顶数字
{
int t1=l.top();
l.pop();
int t2=l.top();
l.pop();
char c;
c=k.top();
k.pop();
int t=operating(t2,t1,c);///计算数值
l.push(t);
k.push(a[i]);
}
else if(a[i]=='*' || a[i]=='/' || a[i]=='%')
{
if(k.top()=='*' || k.top()=='/' || k.top()=='%')///优先级小于栈顶运算符
{
int t1=l.top();
l.pop();
int t2=l.top();
l.pop();
char c;
c=k.top();
k.pop();
int t=operating(t2,t1,c);///计算数值
l.push(t);
k.push(a[i]);
}
else k.push(a[i]);
}
}
while(k.size())///剩余运算符运算
{
int t1=l.top();
l.pop();
int t2=l.top();
l.pop();
char c=k.top();
k.pop();
int t=operating(t2,t1,c);///计算数值
l.push(t);
}
cout<<l.top()<<endl;
}
return 0;
}