zoukankan      html  css  js  c++  java
  • C语言 设一个函数process,调用它时,实现不同功能。

    //凯鲁嘎吉 - 博客园 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 }

    结果为:

  • 相关阅读:
    SQLite基础-7.子句(一)
    SQLite基础-8.子句(二)
    SQLite基础-6.运算符
    SQLite基础-5.数据操作语言
    SQLite基础-4.数据定义语言(DDL)
    SQLite基础-3.语法与数据类型
    IDEA操作之FileHeager设置
    IDEA操作之test case coverage的方法
    IDEA插件之JavaDoc
    IDEA插件之JProfiler
  • 原文地址:https://www.cnblogs.com/kailugaji/p/8592214.html
Copyright © 2011-2022 走看看