编程实现简单的计算器功能,要求用户按如下格式从键盘输入算式:

编程实现简单的计算器功能,要求用户按如下格式从键盘输入算式:
操作数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;
}

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值