[英]C function to find largest element in an array of integers
考慮C函數
int largest(int list[], int n, int l);
list
是n
整數的列表。 l
是函數的臨時空間 該函數應該返回數組list
中n
整數列表中的最大整數。
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.