加减乘除

题目描述:
根据输入的运算符对输入的整数进行简单的整数运算。 运算符只会是加+、减-、乘*、除/、求余%、阶乘!六个运算符之一。 输出运算的结果,如果出现除数为零,则输出“error”,如果求余运算的第二个运算数为0,也输出“error”。

输入描述:
输入为一行。先输入第一个整数,空格输入运算符,然后再空格输入第二个整数,回车结束本次输入。
如果运算符为阶乘!符号,则不输入第二个整数,直接回车结束本次输入。

输出描述:
可能有多组测试数据,对于每组数据,
输出一行。输出对输入的两个(或一个)数,根据输入的运算符计算的结果,或者“error”。

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;

void jiecheng(int x){
    int sum = 1;
    while(x){
        sum *= x;
        --x;
    }
    printf("%d\n", sum);
}

int main(){
    int a, b;
    char x;
    while(~scanf("%d %c", &a, &x)){
        if(x == '!'){
            jiecheng(a);
        }else{
            scanf("%d", &b);
            if(x == '+')printf("%d\n", a + b);
            else if(x == '-')printf("%d\n", a - b);
            else if(x == '*')printf("%d\n", a * b);
            else if(x == '/'){
                if(b == 0){
                    printf("error\n");
                }else{
                    printf("%d\n", a / b);
                }
            }
            else if(x == '%'){
                if(b == 0){
                    printf("error\n");
            }else{
                    printf("%d\n", a % b);
                }
          }
        }
    }
    return 0;
}

改进:

#include<iostream>
using namespace std;

int fac(int a)
{
    int res = 1;
    for(int i=1;i<=a;i++)
        res *=i;
    return res;
}

int main()
{
    char op;
    int a,b;
    while(cin>>a>>op)
    {
    	if(op!='!') cin>>b;
        if(op=='/'&&b==0){
            cout<<"error"<<endl;
            continue;
        }
        if(op=='%'&&b==0){
            cout<<"error"<<endl;
            continue;
        }
        int ans = 0;
        switch(op){
            case '+':ans = a+b;break;
            case '-':ans = a-b;break;
            case '*':ans = a*b;break;
            case '/':ans = a/b;break;
            case '%':ans = a%b;break;
            case '!':ans = fac(a);break;
        }
        cout<<ans<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值