我的任务是:创建一个方法来搜索一个无序的整数数组, 如果找到该值,则返回其在数组中的位置索引,如果未找到,则返回-1。
如果它在索引0中,它只找到我输入的数字,否则就是说找不到它。我不知道出了什么问题,当我初始化我自己的数组时它正在工作,但现在它不会因为我让用户创建自己的数组而赢了。
任何帮助都会很棒!谢谢!
到目前为止,我的代码是:
#include <iostream>
using namespace std;
//SearchArray prototype
int SearchArray( int arInt[], int elementAmount, int intSearched);
int main()
{
int arInt[50];
int elementAmount;
int intSearched = 0;
int i;
cout << "How many elements would you like to add to your array?\n";
cin >> elementAmount;
for( i = 0; i < elementAmount; i++)
{
cout << "Enter Number: ";
cin >> arInt[i];
}
cout << "Search array for integer:\n";
cin >> intSearched;
//Call search array method
SearchArray(arInt, elementAmount, intSearched);
system("pause");
return 0;
}
int SearchArray( int arInt[], int elementAmount, int intSearched)
{
int i;
bool foundInt = false;
for (i=0; i < elementAmount; i++)
{
if( arInt[i] == intSearched)
{
foundInt = true;
cout << "Integer was found in array at index " << i << endl;
}
else if (!foundInt)
{
cout << "Integer was not found in array\n";
system("pause");
return -1;
}
}
}
答案 0 :(得分:0)
在代码中的SearchArray
方法中添加了以下代码,并且工作正常
int SearchArray( int arInt[], int elementAmount, int intSearched)
{
for(int i=0; i< elementAmount; i++)
{
if (arInt[i] == intSearched)
return i;
}
// element not found!
return -1;
}
在main
的末尾添加以下内容以检索ans
int ans = SearchArray(arInt, elementAmount, intSearched);
cout<<"Indexed of the element"<<ans<<endl;
答案 1 :(得分:0)
那是因为你总是在第一个元素上结束你的搜索。假设数组是
arr=[3,5,7] and intSearched is 5.
现在您的SearchArray()
函数foundInt
最初设置为false。因此,当i = 0 and arInt[i] == intSearched
条件不成立时,它会转到else
语句,因为foundInt
是false
。然后从那里返回-1
。像下面这样的东西会更简单并完成工作:
int SearchArray(int *arInt, int elementAmount, int intSearched)
{
int i;
for(i=0; i < elementAmount; i++)
{
if(arInt[i] == intSearched)
{
cout << "Integer was found in array at index " << i << endl;
return 1;
}
}
cout << "Integer was not found in array\n";
system("pause");
return 0;
}