用c语言做一个代码,实现一个在数组中查找指定元素的简单函数。使用函数接口 int search( int list[], int n, int x )
时间: 2023-06-01 17:06:09 浏览: 53
好的,我了解了您的要求。以下是使用 C 语言实现一个查找指定元素的简单函数的代码示例:
```
#include <stdio.h>
int search(int list[], int n, int x) {
int i;
for (i = 0; i < n; i++) {
if (list[i] == x) {
return i;
}
}
return -1;
}
int main() {
int list[] = {2, 7, 1, 9, 5};
int n = sizeof(list) / sizeof(list[0]);
int x = 9;
int index = search(list, n, x);
if (index == -1) {
printf("%d not found\n", x);
} else {
printf("%d found at index %d\n", x, index);
}
return 0;
}
```
函数 `search` 接受一个整数数组、数组长度和要查找的元素,返回该元素在数组中的索引,如果未找到则返回 -1。在 `main` 函数中,我们定义了一个整数数组,然后调用函数 `search` 查找数组中是否包含元素 9,最后打印结果。
以上是一个简单的 C 语言代码示例,希望能够对您有所帮助。
相关问题
用c语言做一个代码,实现一个在数组中查找指定元素的简单函数。使用函数接口 int search( int list[], int n, int
target),其中list是存储元素的数组,n是数组的长度,target是要查找的元素。函数返回值是指定元素的下标,如果数组中不存在该元素,则返回-1。
以下是实现该函数的代码:
```
int search(int list[], int n, int target){
for(int i=0; i<n; i++){
if(list[i] == target)
return i; // 返回指定元素的下标
}
return -1; // 数组中不存在该元素
}
```
用c语言写一个在数组中查找指定元素的简单函数
好的,您可以参考以下代码:
```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 i;
}
return -1;
}
int main(void) {
int arr[] = {3, 4, 1, 7, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 7;
int result = search(arr, n, x);
if (result == -1)
printf("%d not found in the array.\n", x);
else
printf("%d is found at index %d.\n", x, result);
return 0;
}
```
这个函数接受三个参数:一个整数数组、数组的长度和要查找的元素。它使用循环遍历数组,如果找到指定元素就返回它在数组中的索引,否则返回-1表示找不到。在main函数中,我们定义了一个整数数组,然后调用search函数来查找7在数组中的位置,并输出结果。