题目描述:
输入一个数n,然后输入n个数值各不相同,再输入一个值x,输出这个值在这个数组中的下标(从0开始,若不在数组中则输出-1)。
输入
测试数据有多组,输入n(1<=n<=200),接着输入n个数,然后输入x。
输出
对于每组输入,请输出结果。
样例输入
4
1 2 3 4
3
样例输出
2
#include<cstdio>
#include<iostream>
#include<cassert>
#include<string>
#include<fstream>
using namespace std;
const int maxn = 205;
int a[maxn]={0};
int main(){
ifstream in;
in.open("test.txt");
assert(in.is_open());
int n,x;
while(!in.eof()){
in >> n;
for(int i = 0; i <n ; ++i){
in >> a[i];
}
in >> x;
}
for(int i = 0 ; i < n; ++i){
if(a[i] == x) {
printf("%d",i);
in.close();
return 0;
}
}
printf("-1");
in.close();
return 0;
}
本文介绍了一个简单的数组查找算法实现,通过输入一个数n,n个数值及目标值x,输出x在数组中的下标,若不存在则返回-1。代码使用C++编写,通过文件读取测试数据,适用于小规模数据查找。
6万+

被折叠的 条评论
为什么被折叠?



