C语言示例一:利用函数指针数组编写一个计算器(能够实现加减乘除)

利用函数指针数组编写一个计算器(能够实现加减乘除)

#include<stdio.h>

int add(int a,int b){
	return a+b;
}

int minus(int a,int b){
	return a-b;
}

int mutiple(int a,int b){
	return a*b;
}

int devide(int a,int b){
	return a/b;
}

int (*fn[])(int,int)={add,minus,mutiple,devide};

void menu()
{
	printf("*************************************\n");
	printf("***** 1.add            2.minus ******\n");
	printf("***** 3.multiple       4.devide *****\n");
	printf("**********      5.exit    ********** \n");
	printf("*************************************\n");
}

int main(){
	int chose;
	while(1){
		 menu();
		scanf("%d",&chose);
		if(chose<1||chose>=6){
			printf("The Index Is Invalid! please input right index!\n\n");
		}
		switch(chose){
		int op1,op2;
		case 1:
			printf("input two numbers:\n");
			scanf("%d %d",&op1,&op2);
			printf("result=%d\n",fn[0](op1,op2));
			break;
		case 2:
			printf("input two numbers:\n");
			scanf("%d %d",&op1,&op2);
			printf("result=%d\n",fn[1](op1,op2));
			break;
		case 3:
			printf("input two numbers:\n");
			scanf("%d %d",&op1,&op2);
			printf("result=%d\n",fn[2](op1,op2));
			break;
		case 4:
			printf("input two numbers:\n");
			scanf("%d %d",&op1,&op2);
			printf("result=%d\n",fn[3](op1,op2));
			break;
		case 5:
			printf("exit successful\n");
			exit(0);
		}
	}
}
展开阅读全文
©️2020 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值