1. 程式人生 > >簡單用函式指標陣列和回撥函式實現計算器

簡單用函式指標陣列和回撥函式實現計算器

利用函式指標陣列簡單實現計算器

函式指標陣列:以char *(*p[3])(char *)為例解釋,這是一個數組,陣列名為p,陣列記憶體儲了3個指向函式的指標

這些指標指向一些返回值型別為指向字元的指標、引數為一個指向字元的指標的函式

#include<stdio.h>
#include<Windows.h>

#pragma warning (disable:4996)

int add(int x, int y)//加法
{
	return x + y;
}

int sub(int x, int y)//減法
{
	return x - y;
}

int mul(int x, int y)//乘法
{
	return x*y;
}

int mydiv(int x, int y)//除法
{
	if (y == 0)
	{
		printf("Deno cant not be zero!");//分母不能為零
		return 0;
	}
	return x / y;
}

int main()
{
	while (1)
	{
		printf("*********************************\n");
		printf("************  1、ADD  ***********\n");
		printf("************  2、SUB  ***********\n");
		printf("************  3、MUL  ***********\n");
		printf("************  4、DIV  ***********\n");
		printf("************  5、EXIT ***********\n");
		printf("*********************************\n");

		int select = 0;
		printf("Please select:");
		scanf("%d", &select);

		int(*p[4])(int, int);//定義函式指標陣列,轉移表
		p[0] = &add;//p[0]=add也可以  
		p[1] = &sub;
		p[2] = &mul;
		p[3] = &mydiv;

		if (select > 0 && select < 5)
		{
			int x, y;
			printf("Please enter operand <x,y>:");
			scanf("%d %d", &x, &y);//輸入運算元
			int ret = p[select - 1](x, y);//陣列從0~4,輸入從1~5,所以需要減1
			printf("%d\n", ret);
		}
		else if (select == 5)//輸入5,退出
		{
			printf("Bye bye~~\n");
			break;
		}
		else
		{
			printf("Input data is error!");//輸入錯誤
		}
	}
	system("pause");
	return 0;
}


函式指標:函式指標就是函式的指標,它是一個指標,指向一個函式。例:char * (*pf)(char * , char * )

函式指標陣列的指標:例:char * (*(*pf)[3])(char * p);

利用回撥函式簡單實現計算器

#include<stdio.h>
#include<assert.h>
#include<Windows.h>

#pragma warning (disable:4996)

int add(int x, int y)
{
	return x + y;
}

int sub(int x, int y)
{
	return x - y;
}

int mul(int x, int y)
{
	return x*y;
}

int mydiv(int x, int y)
{
	if (y == 0)
	{
		printf("Deno cant not be zero!");
	}
	return x / y;
}

int cal(int x, int y, int (*f)(int,int))//定義函式指標
{
	assert(f);
	int ret = (*f)(x, y);
	printf("%d\n", ret);
}

int main()
{
	while (1)
	{
		printf("*********************************\n");
		printf("************  1、ADD  ***********\n");
		printf("************  2、SUB  ***********\n");
		printf("************  3、MUL  ***********\n");
		printf("************  4、DIV  ***********\n");
		printf("************  5、EXIT ***********\n");
		printf("*********************************\n");

		int select = 0;
		printf("Please select:");
		scanf("%d", &select);

		if (select > 0 && select < 5)
		{
			int x, y;
			printf("Please enter the operand <x,y>:");
			scanf("%d %d", &x, &y);

			switch (select)
			{
			case 1:
			{
				 cal(x, y, add);//回撥函式
			}
				break;
			case 2:
			{
				cal(x, y, sub);
			}
				break;
			case 3:
			{
				cal(x, y, mul);
			}
				break;
			case 4:
			{
				cal(x, y, mydiv);
			}
				break;
			default:
				break;
			}
		}
		else if (select == 5)
		{
			printf("Bye bye~~\n");
			break;
		}
		else
		{
			printf("Input data is error!\n");
			continue;
		}
	}

	system("pause");
	return 0;
}