用函数指针数组的方式来实现简单的两位数计算器

        今天学习了函数指针,和函数指针数组,然后跟着B站大佬比特鹏哥学了一下如何简单的实现计算器,请看代码:

#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
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 divm(int x, int y)
{
	return x / y;
}
void menu(void)
{
	printf("1.+\n");
	printf("2.-\n");
	printf("3.*\n");
	printf("4./(只能整除)\n");
	printf("0.exit\n");
	printf("\n");
}
int main()
{
	int (*arr[5])(int, int) = { 0,add,sub,mul,divm };
	int n;
	do
	{
		menu();
		printf("你想进行什么运算?\n");
		scanf("%d", &n);
		printf("按任意键继续-->\n");
		_getch();
		system("cls");
		if (n == 0)
		{
			printf("程序退出,感谢使用!\n");
		}
		else if (n >= 1 && n <= 4)
		{
			printf("请输入两个值\n");
			printf("按任意键继续-->\n");
			_getch();
			system("cls");
			int x, y;
			scanf("%d%d", &x, &y);
			printf("结果是%d\n", arr[n](x, y));
			Sleep(500);
			printf("按任意键继续-->\n");
			_getch();
			system("cls");
		}
		else
		{
			printf("选择错误,请重新选择!\n");
			Sleep(500);
			printf("按任意键继续-->\n");
			_getch();
			system("cls");
		}
	} while (n);
	return 0;
}

        这个,明天有考试昂,所以说就先不讲解了,等到周末我们慢慢来解决这些伏笔 

你可能感兴趣的:(c语言)