C语言函数指针示例

 

 

 1 #include <stdio.h>
 2 
 3 double add(double a, double b)
 4 {
 5     return a + b;
 6 }
 7 
 8 double sub(double a, double b)
 9 {
10     return a - b;
11 }
12 
13 double mul(double a, double b)
14 {
15     return a * b;
16 }
17 
18 double div(double a, double b)
19 {
20     return a / b;
21 }
22 
23 typedef double (*func)(double, double);
24 
25 double calc(double a, double b, func oper)
26 {
27     double c;
28     c = oper(a, b);
29     return c;
30 }
31 
32 double main(double argc, char* argv[])
33 {
34     double a = 1234.565, b = 36.45, c;
35 
36     c = calc(a, b, add);
37     printf("加法运算: %f + %f = %f\n", a, b, c);
38 
39     c = calc(a, b, sub);
40     printf("减法运算: %f - %f = %f\n", a, b, c);
41 
42     c = calc(a, b, mul);
43     printf("乘法运算: %f * %f = %f\n", a, b, c);
44 
45     c = calc(a, b, div);
46     printf("除法运算: %f / %f = %f\n", a, b, c);
47 
48     return 0;
49 }

 

posted @ 2022-11-10 16:17  O青梅煮酒O  阅读(66)  评论(0编辑  收藏  举报