编写一个名为findx的函数,该函数的参数p指向一个int数组,数组的容量n由参数2指定。在该数组中,查找数据x所在的位置。如果数据x有出现多次,则返回其最后一次出现的位置对应的下标。如果没有找到,则固定返回-2。 int findx(int *p,int n,int x);
时间: 2023-05-02 22:02:51 浏览: 74
该函数名为findx,该函数的参数p指向一个int类型的数组,n表示该数组的容量,而参数x是指向一个int类型的数字的指针,该数字是要在该数组中查找的目标值。在该数组中,查找数字x出现的位置。如果查找到了,则返回该数字在该数组中的位置(下标),如果没有找到,则返回-2。
相关问题
用C语言编写一个程序要求用到函数int find(int *p,int n,int x),在指针p所指的数组中查找整型数x,如果x在数组中,则该函数返回1,否则返回0。n为数组的大小。
好的,我来帮您编写这个程序:
```
#include <stdio.h>
int find(int *p, int n, int x);
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 3;
int result = find(arr, n, x);
if (result == 1)
{
printf("%d is found in the array.\n", x);
}
else
{
printf("%d is not found in the array.\n", x);
}
return 0;
}
int find(int *p, int n, int x)
{
for (int i = 0; i < n; i++)
{
if (*(p + i) == x)
{
return 1;
}
}
return 0;
}
```
在这个程序中,我们定义了一个`find`函数来查找整型数x是否在指针p所指的数组中。在`main`函数中,我们定义了一个整型数组`arr`,数组大小为`n`,要查找的整数为`x`。调用`find`函数来判断`x`是否在`arr`数组中,并根据结果输出相应的信息。
在`find`函数中,我们使用了一个`for`循环来遍历数组中的每一个元素。如果找到了`x`,则返回1,否则返回0。在数组中查找元素需要注意的是,我们使用指针来访问数组元素,即使用`*(p + i)`来代替`p[i]`,这两种写法是等价的。
用C语言指针写一个程序:编写函数int find(int *p,int n,int x),在指针p所指的数组中查找整型数x,如果x 在数组中,则该函数返回1,否则返回0。n为数组的大小。
好的,以下是程序的代码:
```c
#include <stdio.h>
int find(int *p, int n, int x) {
int i;
for(i = 0; i < n; i++) {
if(*(p + i) == x) {
return 1;
}
}
return 0;
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int x = 3;
if(find(arr, 5, x)) {
printf("%d is found in the array.\n", x);
} else {
printf("%d is not found in the array.\n", x);
}
return 0;
}
```
在这个程序中,我们定义了一个 `find` 函数,该函数接受一个指向整型数组的指针 `p`,数组的大小 `n`,以及要查找的整数 `x`。在函数中,我们使用一个 `for` 循环来遍历整个数组,如果找到了要查找的整数 `x`,则返回1,否则返回0。
在 `main` 函数中,我们定义了一个长度为5的整型数组 `arr` 和要查找的整数 `x`。然后,我们调用 `find` 函数来查找 `x` 是否在数组 `arr` 中。如果 `find` 函数返回1,则打印 “x is found in the array.”,否则打印 “x is not found in the array.”。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)