如果它与用户定义的数字匹配,我将尝试返回数组的索引。我不明白为什么,无论我输入什么,函数都会返回“2”。
#include <iostream>
using namespace std;
int search(int x, int *list);
int main()
{
int x;
int list[10] = { 20, 1, 18, 3, 16, 5, 14, 7, 12, 9};
cout << "Enter a number to search the list for: ";
cin >> x;
cout << endl;
cout << search(x, &list[10]) << endl;
system("PAUSE");
return 0;
}
int search(int x, int *list)
{
bool match = false;
for (int i = 0; i < 10; i++)
{
if (list[i] == x)
{
match = true;
}
if (match == true)
{
return i;
}
else if (match == false && i == 9)
{
return -1;
}
}
}
最佳答案
因为您通过从索引 10 开始搜索调用了未定义的行为:
search(x, &list[10])
应该是 search(x, list)
。
...以及循环中的整个 else if
是怎么回事。为什么不在函数末尾返回 -1。以及为什么要有一个 match
变量 - 如果找到匹配项,则返回 i
。
for (int i = 0; i < 10; i++)
{
if (list[i] == x)
{
return i;
}
}
return -1;
关于c++ - 为什么我的函数总是返回 "2"?试图在数组中找到搜索数字的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39322556/