ZOJ 3782 - Ternary Calculation

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.

 

分析:简单模拟 ,各种符号的运算单独开一个函数就好。

自己需要注意的问题:cin>>  输入的时候 空格和回车符不会被读入,但会留在缓冲区。

如果用scanf读入单个字符需要清理缓冲区 cin>>读入单个字符的话如果缓冲区里只有空格和回车就不用清理缓冲区。

代码如下:

#include <bits/stdc++.h> 
using namespace std;
char  s[100];
int cal(int a,int  b,char ch)
{
        if(ch=='+')
        return a+b;
      else if(ch=='-')
      return a-b;
      else if(ch=='*')
      return a*b;
      else if(ch=='/')
      return a/b;
      else if(ch=='%')
      return a%b;
}
int main()
{ 
  std::ios::sync_with_stdio(false);
  int t,sum1,sum2;
  while(cin>>t)
  {
  while(t--)
  {
      int sum=0;
     int a,b,c;
     char ch1,ch2;
     cin>>a>>ch1>>b>>ch2>>c;  
     if((ch1=='+'||ch1=='-')&&(ch2=='*'||ch2=='/'||ch2=='%'))
       {
           sum=cal(b,c,ch2);
           sum=cal(a,sum,ch1);
       }
       else 
       {
           sum=cal(a,b,ch1);
           sum=cal(sum,c,ch2);
       }
     cout<<sum<<endl;  
  }
}
    return 0;
}

 

posted @ 2017-04-19 17:01  hinata_hajime  阅读(119)  评论(0编辑  收藏  举报