导航

面试记录05:编写函数找出数组内最大和最小元素

Posted on 2020-06-27 11:42  ErgoCogito  阅读(794)  评论(0编辑  收藏  举报

题目:
通过C语言,基于以下语句编写一函数,可以找出数组中最大值和最小值

void SearchMax_Min(unsigned char arr[],int len,unsigned char* max,unsigned char* min)

 

答案:

 1 void SearchMax_Min(unsigned char arr[], int len, unsigned char *max, unsigned char *min)
 2 {
 3     *max = arr[0];
 4     *min = arr[0];
 5     for (int i = 1; i < len; i++)
 6     {
 7             if (arr[i] > *max)
 8             {
 9                 *max = arr[i];
10             }
11             else if (arr[i] < *min)
12             {
13                 *min = arr[i];
14             }
15     }
16 }

 

完整程序:

 1 #include <stdio.h>
 2 
 3 void SearchMax_Min(unsigned char arr[], int len, unsigned char *max, unsigned char *min)
 4 {
 5     *max = arr[0];
 6     *min = arr[0];
 7     for (int i = 1; i < len; i++)
 8     {
 9             if (arr[i] > *max)
10             {
11                 *max = arr[i];
12             }
13             else if (arr[i] < *min)
14             {
15                 *min = arr[i];
16             }
17     }
18 }
19 
20 int main()
21 {
22     unsigned char a[]  = {18,28,8,6,68,16,9};
23     unsigned char big, small ;
24     //printf("big : %d\nsmall : %d\n", big, small); big和small刚被赋值时是一个随机值。
25     int len = sizeof(a) / sizeof(char) ;
26     SearchMax_Min(a, len, &big, &small) ;
27     printf("max : %d\nmin : %d", big, small) ;
28     return 0 ;
29 }

 相关联知识点:C语言程序设计-现代方法 第11章第4节 指针作为参数