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

标签 c testing

考虑 C 函数

int largest(int list[], int n, int l);
  • list 是一个 n 个整数的列表。
  • 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);

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

关于C函数查找整数数组中的最大元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23257427/

相关文章:

c - 通过数组的最有效方法?

c - 由 main() 修改并由 ISR() 访问的全局变量

c - c 中的 Exec 函数在应该返回 -1 时没有返回

java - 如何更改 Maven 2/Cobertura 工具目标的默认输出?

php - symfony3中的功能测试,提交表单后访问容器

python - 即使 python/django 中的值相同,assertEqual 也会失败

bash - 测试变量是否为整数

c - 我写了一个程序来打印所有素数直到给定一个数字

testing - 功能测试,为什么只是黑盒?

c - C程序中的非法初始化