我一直试图在过去2个小时内调试此代码。该函数应该简单地在数组元素中找到目标。 这是一个问题:在阵列中查找目标int
//写入一个函数,它的原型如下: bool f2(int a[], int N, int target);
的功能测试目标是否出现的整数数组a
(大小N
的)在至少一个时间。如果 是,则该函数返回true;否则,它返回false。 使用定义五个整数数组的主程序测试函数,并在主程序中初始化它们 ,调用函数f2()
并基于返回值f2()
显示适当的消息。
#include <iostream>
using namespace std;
bool f2(int a[], int n, int target, int& index);
int main(){
int arr[5];
int target;
int index = 0;
cout << " Enter array elements: " << endl;
for (int i = 0; i < 5; i++)
{
cout << " x[" << i << "]: ";
cin >> arr[i];
}
cout << " Enter target to search for : ";
cin >> target;
if (f2(arr, 5, target, index))
cout << " Target " << target << " found in index " << index << endl;
else
cout << " NOT found ! " << endl;
return 1;
}
bool f2(int a[], int N, int target, int& index){
int j = 0;
while (j < N)
{
if (target == a[j]) {
index = j;
cout << "list[" << j << "]" << endl;
return true;
}
return false;
j++;
}
}
你忘了你的问题... – Rakete1111
此外,很明显你没有使用调试器。 –
顺便说一句,你的原型不符合要求 – Jarod42