我可以对代码进行哪些更改以查找EX的每个重复元素的位置:12或45代码:
#include < iostream >
using namespace std;
int findnumber ( int Array[] , int keyword , int size ){
for ( int y=0 ; y<size ; y++ )
if ( keyword==Array[y] ) {
return y;
}
return -1; //not found
}
int main ( ){
int my_array[]={12,12,5,6,9,45,5,54,45};
int searchinput;
cout<<"please select number to search from these (12,12,5,6,9,45,5,54,45) : ";
cin>>searchinput;
int result. = findnumber (my_array , searchinput , 9);
if(result>=0){
cout<<"The number "<<my_array[result]<<" was found in index of : "<<result<<endl;
}
else
{
cout<<"The number "<<searchinput<<" was not found :( "<<endl;
}
如果不允许使用向量,另一种解决方案是让您的函数接受start和end(size)索引。并在main中执行while循环,以从返回的前一个索引+ 1开始搜索。(请注意,这种技术通常可以与STL算法一起使用,例如std::find
)
int findnumber(int Array[], int keyword, int start, int size) {
for (int y = start; y < size; y++) {
if (keyword == Array[y]) {
return y;
}
}
return -1; //not found
}
int main() {
int my_array[] = { 12,12,5,6,9,45,5,54,45 };
int searchinput;
cout << "please select number to search from these (12,12,5,6,9,45,5,54,45) : ";
cin >> searchinput;
int result = findnumber(my_array, searchinput, 0, 9);
if (result >= 0) {
while (result >= 0) {
cout << "The number " << my_array[result] << " was found in index of : " << result << endl;
result = findnumber(my_array, searchinput, result+1, 9);
}
} else {
cout << "The number " << searchinput << " was not found :( " << endl;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句