线性查找:在长度为n的一维数组中查找值为value的元素

//在长度为n的一维数组中查找值为value的元素,即从数组的第一个元素开始,逐个与被查值value比较。

#include<iostream> using namespace std; const int i = 5; // 数组大小 int search(int list[], int num, int value) // value为被查值 { for (int i = 0; i < num; i++) if (value == list[i]) return i; return -1; } int main() { int a[i] = { 43,87,89,453,258 }; int result; // 查找结果 int x; // 待查找的值 cout << "请输入要查找的数:" << endl; cin >> x; result = search(a, i, x); if (-1 == result) cout << "没有找到:" << x << endl; else cout << x << " 是数组的第" << (result + 1) << "个元素" << endl; return 0; }

 程序输出:

 

posted @ 2020-04-27 13:21  萧竹影丶  阅读(27)  评论(0)    收藏  举报