Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 函数来查找整数数组中的最大元素_C_Testing - Fatal编程技术网

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

C 函数来查找整数数组中的最大元素,c,testing,C,Testing,考虑C函数 int largest(int list[], int n, int l); 列表是由n个整数组成的列表。 l是函数的临时空间 函数应该返回数组列表中n个整数列表中的最大整数 为什么此函数有时返回错误数据?在我看来,您似乎试图打印值l,但实际上并没有存储函数的返回值。另外,不需要将l作为参数传递给函数 改为这样做: // Declare the function prototype without int l. int largest(int list[], int n

考虑C函数

int largest(int list[], int n, int l);
列表是由n个整数组成的列表。 l是函数的临时空间 函数应该返回数组列表中n个整数列表中的最大整数


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

在我看来,您似乎试图打印值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;
   }

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

您从不初始化l,因此如果列表中没有任何项大于它,它将返回该值的现有值。如果您从未在调用函数中初始化它,那么行为是未定义的,这将解释错误的数据。

函数返回错误的输入?请显示错误的数据。l参数没有意义。如果它是一个指针,您可以对它进行有效的写入。就目前情况而言,这只是一种阻碍。像你一样使用局部变量。此外,还应设置l=list[0];在开始循环之前。如何调用函数?这是GIGO的实际应用吗?不要破坏你的问题,尤其是在别人给你提供答案之后!如果n是0?我更喜欢int l=int_MIN;fori=0。。。但有些人可能会收到错误消息并退出1。我可以谦虚地建议不要使用l作为变量名。。特别是当我和我在附近的时候@rici你的观点很明智。我希望OP对他的问题足够关心,能够理解其中的可能性。马特,我通常不会用l,我完全明白1和我长得有多像!不过我想在这次行动中保持一致。
   // 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);