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<stdio.h>
#include<stdlib.h>
int s[1001];
int main()
{
int n;
scanf("%d",&n);
char a2,a4;
int a1,a3,a5;
for(int i=1;i<=n;i++)
{
int d=0,e=0;
//if(i==1){getchar();}
scanf("%d %c %d %c %d",&a1,&a2,&a3,&a4,&a5);
if((a2=='+'||a2=='-')&&(a4=='*'||a4=='/'||a4=='%'))
{
if(a4=='*')
{
d=a3*a5;
}
else if(a4=='/')d=a3/a5;
else if(a4=='%')d=a3%a5;
if(a2=='+')
{
e=a1+d;
}
else if(a2=='-')
{
e=a1-d;
}
}
else if((a2=='+'||a2=='-')&&(a4=='+'||a4=='-'))
{
if(a2=='+')
{
d=a1+a3;
}
else if(a2=='-')
{
d=a1-a3;
}
if(a4=='+')
{
e=d+a5;
}
else if(a4=='-')
{
e=d-a5;
}
}
else if((a2=='*'||a2=='/'||a2=='%')&&(a4=='+'||a4=='-'||
a4=='*'||a4=='/'||a4=='%'))
{
if(a2=='*')
{
d=a1*a3;
}
else if(a2=='/')d=a1/a3;
else if(a2=='%')d=a1%a3;
if(a4=='+')
{
e=d+a5;
}
else if(a4=='-')
{
e=d-a5;
}
else if(a4=='*')
{
e=d*a5;
}
else if(a4=='/')
{
e=d/a5;
}
else if(a4=='%')
{
e=d%a5;
}
}
printf("%d\n",e);
}
return 0;
}