7-57 查找整数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41275621/article/details/79300711

7-57 查找整数(10 分)

本题要求从输入的N个整数中查找给定的X。如果找到,输出X的位置(从0开始数);如果没有找到,输出“Not Found”。

输入格式:

输入在第一行中给出两个正整数N(20)和X,第二行给出N个整数。数字均不超过长整型,其间以空格分隔。

输出格式:

在一行中输出X的位置,或者“Not Found”。

输入样例1:

5 7
3 5 7 1 9

输出样例1:

2

输入样例2:

5 7
3 5 8 1 9

输出样例2:

Not Found
#include <stdio.h>

int search(int temp[], int key, int len);
int main()
{
	int n,key;
	scanf("%d %d",&n,&key);
	int temp[n];
	for(int i = 0;i < n; i++)
	{
		scanf("%d",&temp[i]);
	}
	//设置search函数 
	int len = sizeof(temp)/sizeof(temp[0]);//传入函数的数组长度 
	int ans = search(temp,key,len);//将函数输出结果赋给ans 
	if(ans == -1){
		printf("Not Found");
	}
	else{
		printf("%d",ans);
	}
	
	return 0;
}

int search(int temp[], int key, int len)
{
	int ret = -1;
	for(int i = 0; i < len;i++){
		if(temp[i] == key){
			ret = i;
		}
	}
	return ret;
}

猜你喜欢

转载自blog.csdn.net/weixin_41275621/article/details/79300711