//凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/
输入a, b,第一次调用process找最大值,第二次调用process找最小值,第三次调用求和。
方法1:
1 #include<stdio.h> 2 //求最大 3 int max(int x,int y){ 4 return x>y?x:y; 5 } 6 //求最小 7 int min(int x,int y){ 8 return x<y?x:y; 9 } 10 //求和 11 int add(int x,int y){ 12 return x+y; 13 } 14 //类似多态 15 void process(int x,int y,int (*fun)){ 16 int z; 17 if(fun==max) 18 z=max(x,y); 19 if(fun==min) 20 z=min(x,y); 21 if(fun==add) 22 z=add(x,y); 23 printf("%d ",z); 24 } 25 26 void main(){ 27 int a,b; 28 printf("Please input a and b: "); 29 scanf("%d %d", &a, &b); 30 printf("max="); 31 process(a,b,max); 32 printf("min="); 33 process(a,b,min); 34 printf("sum="); 35 process(a,b,add); 36 }
方法2:
1 #include<stdio.h> 2 //求最大 3 int max(int x,int y){ 4 return x>y?x:y; 5 } 6 //求最小 7 int min(int x,int y){ 8 return x<y?x:y; 9 } 10 //求和 11 int add(int x,int y){ 12 return x+y; 13 } 14 15 void main(){ 16 int a,b; 17 int (*process)(int, int); 18 19 printf("Please input a and b: "); 20 scanf("%d %d", &a, &b); 21 22 process=max; 23 printf("max=%d ",process(a,b)); 24 25 process=min; 26 printf("min=%d ",process(a,b)); 27 28 process=add; 29 printf("sum=%d ",process(a,b)); 30 }
结果为: