我有以下伪代码,顺序搜索伪代码,我试图理解返回-1的含义。我们为什么要返回-1,有人可以解释一下。
A[n] <-- K
i <-- 0
while A[i] != K do
i = i + 1
if(i<n)
return i;
else
return -1; //What is this mean ?
答案 0 :(得分:5)
返回-1是一种传达代码到达终点而不返回中间的事实的方式。在这种情况下返回-1意味着元素K不存在于数组中。
请注意,返回0不会用于此目的,因为它可能意味着元素出现在第0个索引处。如果你的函数是在中间的某个点可以返回-1的东西,则会选择一些其他返回值来指示失败。
答案 1 :(得分:0)
如果要搜索序列中的元素,并返回该元素的索引,则需要某种方式来显示未找到该元素。负值是许多语言中的无效索引,因此返回-1
只能表示由于某种原因无法找到该元素。
int index_of(const int *array, int sz, int elem) {
for (int i = 0; i < sz; ++i) {
if (array[i] == elem) { // found the element
return i; // return the index of the element
}
}
return -1; // couldn't find it
}
然后在调用代码中你可能有
int calling() {
int array[N];
// populate array with data ...
int idx = index_of(array, N, 4); // find where 4 is in the array
if (idx < 0) {
// 4 isn't in the array
} else {
// 4 IS in the array !
}
}