查找数组中最大值返回其下标
时间: 2023-10-13 10:04:52 浏览: 71
好的,以下是查找数组中最大值返回其下标的 Python 代码实现:
```python
def find_max_index(arr):
max_index = 0
for i in range(1, len(arr)):
if arr[i] > arr[max_index]:
max_index = i
return max_index
```
该函数接受一个数组作为参数,遍历数组中每个元素,找到最大值并记录其下标,最后返回最大值的下标。
相关问题
使用c++查找数组中最大值返回其下标
可以使用以下代码实现:
```c
#include <stdio.h>
int findMaxIndex(int arr[], int length) {
int maxIndex = 0;
for (int i = 1; i < length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
int main() {
int arr[] = {1, 5, 3, 9, 7};
int length = sizeof(arr) / sizeof(arr[0]);
int maxIndex = findMaxIndex(arr, length);
printf("The index of the maximum value is: %d\n", maxIndex);
return 0;
}
```
在这个程序中,`findMaxIndex` 函数遍历数组并记录最大值的下标,然后返回该下标。在 `main` 函数中,我们调用 `findMaxIndex` 函数并打印最大值的下标。
在二维数组中查找最大值及其下标
可以回答。要在二维数组中查找最大值及其下标,可使用双重循环遍历整个数组,并记录下最大值及其下标。以下是一个简单的示例代码:
```
int max_val = arr[0][0];
int max_i = 0;
int max_j = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (arr[i][j] > max_val) {
max_val = arr[i][j];
max_i = i;
max_j = j;
}
}
}
// 最大值为 max_val,其下标为 (max_i, max_j)
```