编写带有函数的程序(函数名为:int fun(int *s,int *n,int len)),功能是求出数组的最大元素在数组中的下标并存放在n所指的存储单元中。
时间: 2023-07-14 08:12:03 浏览: 67
下面是一个示例程序:
```
#include <stdio.h>
int fun(int *s, int *n, int len) {
int max = s[0];
int index = 0;
for (int i = 1; i < len; i++) {
if (s[i] > max) {
max = s[i];
index = i;
}
}
*n = index;
return max;
}
int main() {
int arr[] = {5, 9, 3, 7, 2};
int len = sizeof(arr) / sizeof(int);
int maxIndex = 0;
int max = fun(arr, &maxIndex, len);
printf("The maximum element in the array is %d, and its index is %d.\n", max, maxIndex);
return 0;
}
```
函数 `fun` 接受三个参数:指向数组的指针 `s`,存储最大元素下标的指针 `n`,以及数组长度 `len`。函数使用循环遍历数组中的每个元素,找到最大的元素并记录其下标。最后将最大元素的值返回,并将最大元素的下标存储在 `n` 所指向的存储单元中。
在 `main` 函数中,定义一个整型数组 `arr`,并计算数组的长度。然后调用函数 `fun`,将数组和存储最大元素下标的指针作为参数传递给函数。最后输出最大元素的值和下标。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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://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)