-
Notifications
You must be signed in to change notification settings - Fork 0
/
Callback function
73 lines (70 loc) · 1.23 KB
/
Callback function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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 Div(int x, int y)
{
return x / y;
}
void menu()
{
printf("******************************\n");
printf("****** 1.add 2.sub ******\n");
printf("****** 3.mul 4.div ******\n");
printf("****** 0.exit *******\n");
printf("******************************\n");
}
int Calc(int (*pf)(int,int))//函数指针
{
int x = 0;
int y = 0;
printf("请输入2个操作数:>");
scanf("%d %d", &x, &y);
return pf(x, y);
}
int main()
{
//计算器-计算整型变量的加、减、乘、除
int input = 0;
do
{
menu();
int ret = 0;
printf("请选择:>");
scanf("%d", &input);
switch (input)
{
case 1:
ret = Calc(Add);//回调函数机制
printf("ret = %d\n", ret);
break;
case 2:
ret = Calc(Sub);//回调函数机制
printf("ret = %d\n", ret);
break;
case 3:
ret = Calc(Mul);//回调函数机制
printf("ret = %d\n", ret);
break;
case 4:
ret = Calc(Div);//回调函数机制
printf("ret = %d\n", ret);
break;
case 0:
printf("退出程序\n");
break;
default:
printf("选择错误,重新选择\n");
break;
}
} while (input);
return 0;
}