繁体   English   中英

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

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

考虑C函数

int largest(int list[], int n, int l);
  • listn整数的列表。
  • l是函数的临时空间

该函数应该返回数组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;
}

为什么此函数有时返回错误数据?

在我看来,您正在尝试打印值l但实际上并没有存储该函数的返回值。 同样,您不需要将l作为参数传递给函数。

改为这样做:

   // 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;
   }

然后在调用函数的位置执行以下操作:

int l = largest(list, n);

上面的代码只是确保您存储函数返回的值。

您永远不会初始化l ,因此,如果列表中没有任何项目大于l ,则它将返回this的现有值。 如果您从未在调用函数中对其进行初始化,那么该行为是不确定的,这将解释您的“错误数据”。

暂无
暂无

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

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