三元运算

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值