1,3,5,7,9,8,6,4,2,请写一个函数找出数组最大的元素
时间: 2023-08-17 18:06:08 浏览: 38
好的,根据您的要求,我可以写一个函数来找出数组中的最大元素。以下是使用 Python 语言编写的一个示例函数:
```python
def find_max(arr):
max_num = arr[0]
for i in range(1, len(arr)):
if arr[i] > max_num:
max_num = arr[i]
return max_num
```
您可以将数组作为参数传递给该函数,例如:
```python
arr = [1, 3, 5, 7, 9, 8, 6, 4, 2]
max_num = find_max(arr)
print(max_num)
```
这样就会输出数组中的最大元素 9。
相关问题
自定义函数找出数组中的最大值与最小值——3X4的二维数组
以下是一个示例代码:
```python
def find_max_min(arr):
"""
找出二维数组中的最大值和最小值
:param arr: 二维数组,每行有4个元素
:return: 返回一个元组,第一个元素是最大值,第二个元素是最小值
"""
max_val = arr[0][0]
min_val = arr[0][0]
for row in arr:
for val in row:
if val > max_val:
max_val = val
if val < min_val:
min_val = val
return max_val, min_val
# 测试代码
arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
max_val, min_val = find_max_min(arr)
print("最大值为:", max_val)
print("最小值为:", min_val)
```
输出结果为:
```
最大值为: 12
最小值为: 1
```
该函数首先初始化最大值和最小值为数组中的第一个元素,然后遍历整个数组,逐个比较每个元素与最大值和最小值的大小关系,并更新最大值和最小值。最后将最大值和最小值打包成一个元组返回。在测试代码中,我们使用了一个3X4的二维数组进行测试。
编写一个函数 n=10 找出数组最大元素和最小元素的下标 并在主函数输出最大元素和最小元素下标值
好的,以下是实现代码:
```c
#include <stdio.h>
void find_max_min_index(int arr[], int n, int* max_index, int* min_index)
{
*max_index = *min_index = 0; // 初始化最大和最小元素下标为0
for (int i = 1; i < n; i++)
{
if (arr[i] > arr[*max_index])
{
*max_index = i;
}
else if (arr[i] < arr[*min_index])
{
*min_index = i;
}
}
}
int main()
{
int arr[10] = {1, 5, 3, 7, 9, 2, 8, 4, 6, 0};
int max_index, min_index;
find_max_min_index(arr, 10, &max_index, &min_index);
printf("最大元素下标:%d,最大元素值:%d\n", max_index, arr[max_index]);
printf("最小元素下标:%d,最小元素值:%d\n", min_index, arr[min_index]);
return 0;
}
```
在这个程序中,我们定义了一个函数 `find_max_min_index`,它接受一个整数数组、数组长度以及两个指针,用于存储最大和最小元素的下标。函数内部使用一个循环遍历数组,找出最大和最小元素的下标,并将它们存储在指针所指向的变量中。
在主函数中,我们定义一个长度为10的整型数组,并调用 `find_max_min_index` 函数来查找最大和最小元素的下标。最后,我们使用 `printf` 函数输出最大元素的下标和值,以及最小元素的下标和值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)