簡體   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