我一直試圖在過去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