编写一个简单计算器程序,输入格式为: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;
}