求一维数组中的最大值及最大值所在数组下标
时间: 2023-12-30 14:03:50 浏览: 54
好的,可以使用以下算法来求解:
1. 初始化最大值为数组中的第一个元素,最大值下标为 0。
2. 遍历数组,如果当前元素大于最大值,则更新最大值和最大值下标。
3. 遍历完成后,返回最大值和最大值下标。
以下是实现代码:
```python
def find_max(arr):
max_val = arr[0]
max_idx = 0
for i in range(1, len(arr)):
if arr[i] > max_val:
max_val = arr[i]
max_idx = i
return max_val, max_idx
```
使用示例:
```python
arr = [3, 6, 1, 8, 2, 9, 4]
max_val, max_idx = find_max(arr)
print("最大值为:", max_val)
print("最大值所在数组下标为:", max_idx)
```
输出结果:
```
最大值为: 9
最大值所在数组下标为: 5
```
相关问题
求一维数组中的最大值与最小值的下标
最大值的下标和最小值的下标代码如下:
```python
arr = [3, 9, 2, 7, 5, 8, 1, 6, 4]
max_index = arr.index(max(arr))
min_index = arr.index(min(arr))
print("最大值的下标为:", max_index)
print("最小值的下标为:", min_index)
```
输出结果为:
```
最大值的下标为: 1
最小值的下标为: 6
```
C语言一维数组求最大值和下标
好的,以下是 C 语言代码实现:
```c
#include <stdio.h>
int main() {
int arr[] = {5, 8, 3, 1, 9, 7, 6};
int n = sizeof(arr) / sizeof(arr[0]);
int max = arr[0];
int index = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
index = i;
}
}
printf("最大值:%d\n下标:%d", max, index);
return 0;
}
```
输出结果如下:
```
最大值:9
下标:4
```
以上代码中,我们首先定义了一个数组 `arr`,并且使用 `sizeof` 函数计算出了数组的长度 `n`。接着,我们定义了变量 `max` 和 `index`,用于储存最大值和下标。然后,我们使用 for 循环遍历数组,如果当前元素大于最大值,则将当前元素赋值给 `max`,并且将当前的下标赋值给 `index`。最后,输出最大值和对应的下标即可。