编程实现简单的计算器功能,要求用户按如下格式从键盘输入算式: 操作数1 运算符op 操作数2 计算并输出表达式的值,其中算术运算符包括:加(+)、减(-)、乘(*)、除(/)。 要求使其能进行浮点数的算术运算,同时允许使用字符*、x与X作为乘号,并且允许输入的算术表达式中的操作数和运算符之间可以加入任意多个空格符。 **输入格式要求:"%f %c%f" 提示信息:"Please enter the expression:\n" **输出格式要求:"%f + %f = %f \n" "%f - %f = %f \n" "%f * %f = %f \n" "%f / %f = %f \n" "Division by zero!\n" "Invalid operator! \n" 程序运行示例1如下: Please enter the expression: 2.0 + 4.0 2.000000 + 4.000000 = 6.000000 程序运行示例2如下: Please enter the expression: 2.0 - 4.0 2.000000 - 4.000000 = -2.000000 程序运行示例3如下: Please enter the expression: 2.0 * 4.0 2.000000 * 4.000000 = 8.000000 程序运行示例4如下: Please enter the expression: 2.0 x 4.0 2.000000 * 4.000000 = 8.000000 程序运行示例5如下: Please enter the expression: 2.0 X 4.0 2.000000 * 4.000000 = 8.000000 程序运行示例6如下: Please enter the expression: 2.0 / 4.0 2.000000 / 4.000000 = 0.5000000 程序运行示例7如下: Please enter the expression: 2.0 / 0 Division by zero! 程序运行示例8如下: Please enter the expression: 2.0 \ 4.0 Invalid operator!
#include<stdio.h>
int main(){
printf("Please enter the expression:\n");
float a , b, d;
char c;
scanf("%f %c%f",&a,&c,&b);
if(c == '+'){
d = a+b;
printf("%f + %f = %f \n",a,b,d);
}else if(c == '-'){
d = a-b;
printf("%f - %f = %f \n",a,b,d);
}else if(c == '/'){
if(b!=0){
d = a/b;
printf("%f / %f = %f \n",a,b,d);
}else printf("Division by zero!\n");
}else if(c == '*'||c == 'x'||c == 'X'){
d = a*b;
printf("%f * %f = %f \n",a,b,d);
}else printf("Invalid operator! \n");
return 0;
}