C语言一个整数在数组中的为主,如果没找到,返回他的下标,否则返回-1,显示没找到
时间: 2024-05-16 15:17:26 浏览: 11
以下是一个示例代码:
```c
#include <stdio.h>
int search(int arr[], int n, int x) {
int i;
for (i = 0; i < n; i++) {
if (arr[i] == x) {
return -1; // 找到了,返回-1
}
}
return i; // 没找到,返回下标 i
}
int main() {
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 6;
int result = search(arr, n, x);
if (result == -1) {
printf("没找到\n");
} else {
printf("下标为 %d\n", result);
}
return 0;
}
```
在这个示例代码中,`search` 函数接收一个整数数组 `arr`,数组长度 `n` 和需要查找的元素 `x`。函数使用循环遍历整个数组,如果找到了 `x`,则返回 -1,表示没找到;如果遍历完整个数组都没有找到 `x`,则返回数组长度 `n`,表示 `x` 在数组中不存在,返回他的下标。
在 `main` 函数中,我们声明了一个整数数组 `arr`,包含了 1 到 5 这几个数字。然后我们调用 `search` 函数,查找数字 6 是否在数组中。最后根据返回值判断是否找到,并输出结果。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)