计算机程序

编写一个简单计算器程序,输入格式为:data1 op data2。其中data1和data2是参加运算的两个数(可以是小数),op为运算符,它的取值只能是+、-、*、/、%之一。输出:求余计算输出整数外,其余运算输出小数点后两位。输入提示为:printf("Please input data1 op data2: ")。scanf()的格式字符需要用空格分开。求余运算只能接受两个整数,如果输入的数据有非零的小数(可以通过将输入数据减去其取整的数据是否为0来判断),如:3.1 % 2,则输出错误信息"The remainder operands must be integers."。求余和除法运算时,除数必须不等于0,否则输出错误信息"The divisor must not be zero."。注意,求余时可能发生的两个输入错误,按先检查整数性,再检查除数是否为0的顺序进行。此外,如果运算符op不正确,如输入的是&,显示错误信息"Operator & is not supported."。

#include <stdio.h>

int main(void)
{
    double d1,d2,n;
    char op;
    printf("Please input data1 op data2: ");
    scanf("%lf %c %lf",&d1,&op,&d2);
    printf("Outputs:\n");
    switch(op)
    {
    case'+':n=d1+d2;printf("%lf %c %lf = %.2lf\n",d1,op,d2,n);break;
    case'-':n=d1-d2;printf("%lf %c %lf = %.2lf\n",d1,op,d2,n);break;
    case'*':n=d1*d2;printf("%lf %c %lf = %.2lf\n",d1,op,d2,n);break;
    case'/':if(d2==0)
                printf("The divisor must not be zero.\n");
            else {n=d1/d2;printf("%lf %c %lf = %.2lf\n",d1,op,d2,n);
            }break;
    case'%':if(d1-(int)d1!=0||d2-(int)d2!=0)
                printf("The remainder operands must be integers.\n");
            else if(d2!=0){n=(int)d1%(int)d2;printf("%.0lf %c %.0lf = %.0lf\n",d1,op,d2,n);}
            else printf("The divisor must not be zero.\n");break;
    default:printf("Operator %c is not supported\n",op);
    }
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值