简体   繁体   English

C函数查找整数数组中的最大元素

[英]C function to find largest element in an array of integers

Consider the C function 考虑C函数

int largest(int list[], int n, int l);
  • list is a list of n integers. listn整数的列表。
  • l is temp space for the function l是函数的临时空间

The function is supposed to return the largest integer in the list of n integers in the array list . 该函数应该返回数组listn整数列表中的最大整数。

int largest(int list[], int n, int l) {
   int i;
   for(i=0; i<n; i++) {
      if(list[i] > l) {
         l = list[i];
      }
   }
   return l;
}

Why is this function returning bad data at times? 为什么此函数有时返回错误数据?

Looks to me like you are trying to print the value l but you are not actually storing the return value of the function. 在我看来,您正在尝试打印值l但实际上并没有存储该函数的返回值。 Also you don't need to pass l as a parameter to your function. 同样,您不需要将l作为参数传递给函数。

Do this instead: 改为这样做:

   // Declare the function prototype without int l.
   int largest(int list[], int n);

   // Actual function that searches for largest int.
   int largest(int list[], int n) 
   {
      int i;
      int l = list[0]; // Point to first element. 

      // Notice loop starts at i = 1.
      for(i = 1; i < n; i++) 
      {
         if(list[i] > l) 
           l = list[i]; 
      }

      return l;
   }

Then where you call your function do this: 然后在调用函数的位置执行以下操作:

int l = largest(list, n);

This code above just ensures that you store the value that your function returns. 上面的代码只是确保您存储函数返回的值。

You never initialize l , so it will return the existing value of this if none of the items in the list were larger than it. 您永远不会初始化l ,因此,如果列表中没有任何项目大于l ,则它将返回this的现有值。 If you never initialized it in the calling function then the behaviour is undefined, which would explain your "bad data". 如果您从未在调用函数中对其进行初始化,那么该行为是不确定的,这将解释您的“错误数据”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM