考虑 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);
上面的代码只是确保您存储函数返回的值。
关于C函数查找整数数组中的最大元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23257427/