再也不用担心算错啦~看看我们实现的计算器吧~(函数指针数组)

首先我们要知道函数指针数组的概念,在这里不在多说,可以去看这篇啦

https://blog.csdn.net/z_juan1/article/details/80410565


接下来说说转移表转移表是将所以函数的地址存放在一个数组中,用访问数组下标的方法去访问函数

在这里我们是来实现一个计算器,首先我们要写一个具体实现功能的方法,然后定义一个函数指针数组,将这些函数放进数组

在通过访问数组下标的方法来调用函数。


#pragma warning(disable:4996)
int my_add(int x, int y)  //基本方法
{
	return x + y;
}
int my_sub(int x, int y)
{
	return x - y;
}
int my_mul(int x, int y)
{
	return x * y;
}
int my_div(int x, int y)
{
	if(y == 0)
	{
		printf("div zero! error!\n");
		return -1;
	}
	return x / y;
}
void menu()                                   //游戏菜单
{
	printf("#####################\n");
	printf("###1.add     2.sub###\n");
	printf("###3.mul     4.div###\n");
	printf("###          0.quit##\n");
	printf("#####################\n");
	printf("please select: ");
}
int main()
{
	int(*p[4])(int, int) = {my_add,my_sub,my_mul,my_div};           //定义函数指针数组,并进行初始化
	int select;
	do{
		menu();
		scanf("%d",&select);
		if (select >= 1 && select <= 4)
		{
			int x, y;
			printf("please enter your data :<x,y>");
			scanf("%d %d", &x, &y);
			int res=p[select-1](x, y);      //函数调用        此时p[select-1]是对数组第select-1个元素进行访问,里面放的是函数的地址。
			printf("result:%d\n", res);
		}
		else if (select == 0)
		{
			printf("bey!\n");
			break;
		}
		else
		{
			printf("you enter select error [1,4]\n");
		}
	} while (1);
	system("pause");
	return 0;
}

运行的结果:


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值