利用函數指針數組簡單實現計算器
函數指針數組:以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] = ⊂
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;
}