int search( int arr[], int size, int num) {
int i, loc;
loc=i;
for (i=0;i<size;i++){
if (arr[i]==num)
return loc;
else
return -1;
}
}
有人能告诉我哪里出错了吗?
回答1
显示的代码存在几个问题,如下所述。
问题 1
变量 i
和 loc
未初始化,使用那些未初始化的变量(您在编写 loc = i
时所做的)是未定义的行为。
问题 2
您用于 for
循环和 if
else
部分的逻辑未正确实现。特别是,假设由于条件 i<size
为假而未进入 for
循环,那么您的非 void 返回函数将不再遇到返回语句,从而导致未定义的行为。
解决方案
无需创建名为 loc
的变量。找到元素后,您可以直接返回 i
。此外,不需要 else
块。如果在遍历元素时未找到该元素,我们只需在 for
循环之后返回 -1
。
int search( int arr[], int size, int num) {
for (int i=0; i < size; i++)
{
if (arr[i]==num)
return i;//value found so return i directly
}
return -1; //value was never found
}
int main()
{
int arr[] = {1,2,33,54,3};
std::cout<<search(arr, 5, 3)<<std::endl; //prints 4
std::cout<<search(arr, 5, 33)<<std::endl; //prints 2
std::cout<<search(arr, 5, 98)<<std::endl; //prints -1
}
回答2
这是解决初始代码中问题的解决方案。让我们通过注释代码来分解它。
int search(int arr[], int size, int num) {
// Initialize `location` to a value, this is very important
// In this case, it's okay to initialize to the "not found"
// value and you can simply `return location` at the end of
// this function.
int location = -1;
for (int index = 0; index < size; index++) {
// Check to see if `arr[index] == num`
// If so, we found `num` in `arr` !
// Otherwise, let the loop continue
if (arr[index] == num) {
// Since we found `num` in `arr`, let's store the index
// by updating our location
location = index;
// We found the index we are looking for
// No need to continue the `for` loop
break;
}
// No need for an `else` here, as it was noted in comments that
// returning in the `else` block would exit your loop early
}
// Just return `location`. It either stores `-1` of the index of `num`
return location;
}
花点时间查看您的解决方案并将其与此特定解决方案进行比较。您的原始代码的主要问题是
- 您没有初始化
loc
变量,也没有在返回之前更新它。这会导致未定义的行为。 - 你有一个
else
语句在你的for
循环中返回-1
,这导致循环只迭代一次
请注意,有几种方法可以编写此函数,我只展示了一种方法。考虑如何使用自己的方法编写功能等效的东西。
另请注意,您可以简化此代码以完全不使用 location
变量,如@AnoopRana 提供的答案所示。我在示例中不再使用 location
变量,因为它似乎更接近您最初的目标。这个解决方案很冗长,旨在帮助您更彻底地理解算法在做什么。
回答3
#include <iostream>
int search(int arr[], int n , int element)
{
int i = 0;
while (i < n)
{
if (arr[i] == element) {
break;
}
i++;
}
if (i < n)
{
return i;
}
else {
return -1;
}
return 0;
}
int main()
{
int arr[] = { 1, 2, 33, 54, 98 };
int n = sizeof(arr)/sizeof(arr[0]);
int element;
std::cout<<"Enter element to search for ";
std::cin>>element;
std::cout<<search(arr,n,element);
}