指针函数实现计算器

普通计算器

#include <stdio.h>
int main()
{
	double a;
	double b;
	char e;
	char i;
	
	do
	{	
		printf("输入+,-,*,/,进行接下来的运算: \n");
		scanf("%c", &e);
		
		printf("输入a, b的值:\n");
		scanf("%lf %lf", &a, &b);
			
		switch(e)
		{	
			case '+':
				printf("%lf + %lf = %lf\n", a, b, a + b);
				break;
			
			case '-':
				printf("%lf - %lf = %lf\n", a, b, a - b);
				break;
				
			case '*':
				printf("%lf * %lf = %lf\n", a, b, a * b);
				break;
			
			case '/':
				
				while(b == 0)
				{
					printf("分母不能为0,请重新输入: ");
					scanf("%lf %lf", &a, &b);
				}
				
				printf("%lf / %lf = %lf\n", a, b, a / b);
				
				break;
			
			default: 
				printf("重新输入\n");
				break;					
		}
		
		getchar();  // 消除回车 
		printf("输入N退出,输入Y继续\n");
		scanf("%c", &i);
		getchar();
		
	}while(i != 'N');
	
	return 0;
}
#include<stdio.h>
int add(int a,int b)
{  
	return a+b;
 } 
 int sub(int a,int b)
{  
	return a-b;
 } 
 int mul(int a,int b)
{  
	return a*b;
 } 
 int div(int a,int b)
{  
	return a/b;
 } 
 int calc(int (*f)(int,int),int a,int b)//定义一个函数指针 
{  
	return (*f)(a,b);
 } 
 
 int main()
 {
 	int a,b;
 	scanf("%d %d",&a,&b);
 	printf("+:%d\n-:%d\n*:%d\n/:%d\n",calc(add,a,b),calc(sub,a,b),calc(mul,a,b),calc(div,a,b));
 	return 0;
 }

(*f)(int,int)是一个函数指针作为calc函数的参数;
函数名add等实际上是一个地址(同数组名一样);

  • 输入:3 4
  • 输出:
  • +:7
  • -:-1
  • *:12
  • /:0

改进

#include<stdio.h>
int add(int a,int b)
{  
	return a+b;
 } 
 int sub(int a,int b)
{  
	return a-b;
 } 
 int mul(int a,int b)
{  
	return a*b;
 } 
 int div(int a,int b)
{  
	return a/b;
 } 
 int calc(int (*f)(int,int),int a,int b)//定义一个函数指针 
{  
	return (*f)(a,b);
 } 
 int (*select(char a))(int,int)
 {
 	switch(a)
 	{
 		case '+':return add;     //不需要break,因为return后已经终止函数了
		case '-':return sub;
		case '*':return mul;
		case '/':return div;
	 }
 }
 int main()
 {
 	int a,b;
 	char c;
 	scanf("%d%c%d",&a,&c,&b);
 	int (*f)(int,int);
 	f=select(c);
 	printf("%d%c%d=%d",a,c,b,calc(f,a,b));
 	return 0;
 }

指针函数和函数指针相结合(原理和数组差不多)
实现计算器

  • 输入:3+4
  • 输出:3+4=7
  • 输入:3*4
  • 输出:3*4=12
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值