设计一个函数,在一个数组中查找指定的元素,找到后返回所在的位置,否则返回-1,求代码。并把我的修改下

#include<stdio.h>
#define NOT_FOUND -1
int search(const int arr[],int target,int n)
{
int i,found,position;
i=0;
while(!found&&i<n)
{
if(target==arr[i])
found=1;
else
++i;
}
if(found)
position=i;
else
position=NOT_FOUND;
return (position);
}

int main()
{
int i,arr[7];
for(i=0;i<7;i++)
scanf("%d",&arr[i]);
printf("%d",search(arr,4,7));
return 0;
}

#include<stdio.h>
#define NOT_FOUND -1
int search(const int arr[],int target,int n)
{
int nPosition = 0 ;
for(int i = 0 ;i < n ;i ++)
{
if(target == arr[i])

{
nPosition = i ;

break ;

}
else

{
nPosition = NOT_FOUND ;

continue ;

}
}
return nPosition;
}

这是那个函数的修改,个人习惯 参考一下!追问

你这个很是简洁,不过你能不能找一下我的错误在哪?

追答

不好意思 试错了 我试的是我写的代码 没有问题 你的代码有问题啊

found没有初始化 根本没有进入while循环 你可以调试一下 跟踪一下代码 就知道问题的所在!

温馨提示:答案为网友推荐,仅供参考
相似回答