我寫了一個基本的線性搜索C++代碼。每當我運行這個時,我得到的結果總是與預期結果相反。
例如,我想要搜索4.在它存在的數組中,它會說沒有找到數字,但是在搜索一個缺失元素時,它會說該元素在位置0找到。C++代碼故障
即使經過一個小時左右的時間,我仍然沒有找到任何解決方案。
#include <iostream>
using namespace std;
//scanning program
int linearsearch (int A[] , int z, int n, int srchElement) {
for (int z = 0; z < n; z++) {
if (A[z] == srchElement) {
return z;
}
}
return -1;
}
//main program
int main() {
int i, n, A[1000], z;
//asking for size of array
cout << "give size of the array needed to be scanned: ";
cin >> n;
cout << endl;
if (n > 999) {
cout << "invalid value";
return -1;
}
//making sure of the size of the array
cout << "enter " << n << " integers: ";
//asking for the array
for (i = 0; i < n; i++) {
cin >> A[i];
}
int srchElement, index;
do {
cout << endl << "enter element to search (-1 to exit): ";
//srchElement is defined here
cin >> srchElement;
if (srchElement == -1) break;
index = linearsearch(A, n, srchElement, z);
//calling thscanning function
if (index == -1) {
cout << srchElement << " not present" << endl;
}
//outputting the results of the scan
else {
cout << srchElement << " present " << index << endl;
}
} while (true);
return 0;
}
這段代碼是絕對不可讀的;你應該格式化它。 – tenfour 2014-10-27 10:38:03