5. 05 C语言 函数

来源:互联网 发布:学java去哪儿好 编辑:程序博客网 时间:2024/05/01 07:20

函数是什么? 

 

常见的库函数都有哪些? 

 

自定义函数的一般形式是什么? 

 

形参和实参是什么? 

 

函数的调用如何实现? 


作业 :  

1动态输入三个整数,写一个函数,返回最大值并输出该值; 

 

int getMax(int x, int y, int z) { 

     

    int temp = 0; 

    temp = x > y ? x : y; 

    return temp > z ? temp : z; 

     

} 

 

2、写一个函数,返回输入整数(大于999小于10000)的每位的数字之和。 

 

int getDigitSum(int n) { 

     

    int result = 0; 

     

    result = n % 10 + n % 100 / 10 + n % 1000 / 100 + n / 1000; 

     

    return result; 

     

} 

 

3、写一个函数,将传入的字符串转为全大写,数字和符号不变。 

 

void uppercase(char str[], unsigned long length) { 

     

    int i = 0; 

     

    while (str[i] != '\0' && i < length) { 

         

        if (str[i] >= 'a' && str[i] <= 'z') { 

            

            str[i] -= 32; 

        } 

       

        i++; 

    } 

    

    puts(str); 

     

} 

 

 

4、写一个函数返回一个int数组中的最大重复数(数组元素的重复次数为该元素在数组中出现的次数),如{1132323}最大重复数为(注意:打印输出的是,重复次数最多,该数的值 

 

方法一:注意,本方法只适用于数组元素全部为非负数的情况。 

//找出最大重复数 (填坑法) 

 

int getMaxRepeat(int arr[], int length) { 

     

    int result = 0; 

    int index = 0; 

    int tempArray[50] = {0}; 

    int max = 0; 

    int maxIndex = 0; 

     

    for (int i = 0; i < length; i++) { 

        

        index = arr[i];     //遍历,arr数组的值做为下标 

         

        tempArray[index]++;  // tempArray[index]对应的值+1 

     

    } 

     

    for (int j = 0; j < 50; j++) { 

         

        if (max < tempArray[j]) { 

             

            max = tempArray[j];   //找到tempArray数组的最大值的位置 

             

            maxIndex = j; 

        } 

        

    } 

     

    result = maxIndex; 

     

    return result; 

} 

 

 

方法二(better): 

 

int getRecur(int array[], int length) { 

     

    // times:当前这个数重复了多少次 

    // max:重复最多的【次数】 

    // theNum:重复次数最多的数 

    int times = 0, max = 0, theNum = array[0]; 

     

    for (int i = 0; i < length; i ++) { 

         

        for (int j = 0; j < length; j ++) { 

             

            if (array[i] == array[j]) { 

                 

                times ++; 

            } 

        } 

         

        if (times > max) { 

             

            max = times; 

            theNum = array[i]; 

        } 

        times = 0; 

    } 

    return theNum; 

} 

 


0 0
原创粉丝点击