您的位置:首页 > 其它

G-Ternary Calculation(字符串模拟题)

2015-03-08 16:47 99 查看
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.



题目的大致意思就是:

给你3个实型整数,然后两个运算符,要你模拟它的过程,然后得出最终的答案。

一开始我想的是分别把这几个运算符存到数组中去,然后判断第几个再进行相应的过程,但是后来发现这样会有错误而且写的很复杂,因为你并没有判断过符号的优先顺序,所以最后算出来的结果可能是错的。

后来我瞄了一下题解,发现可以用暴力枚举法,因为数据量不是很大,所以直接分类就好。

1.oper1是低级的运算符(即为+或是-),oper2是高级的运算符(即为*、/、%),那么就先算第二个然后再算第一个;

2.oper1是低级的,oper2也是低级的,那么直接顺序相加就好。

3.oper1是高级的,oper2是高级的或是低级的,那么也是直接顺序的算过来就好。



#include<stdio.h>
#include<string.h>
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);
	}
}




这种题目也许第一次遇见自己可能会想的稍微久一点,但是积累了思路之后就能慢慢的变得更加强大!加油~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: