一维数组,求最大的元素及其下标,求最大元素用函数实现
时间: 2024-02-18 14:05:52 浏览: 29
好的,针对您的问题,我可以给您提供以下 C++ 代码,其中 getMax() 函数可以用来获取一维数组中的最大元素及其下标:
```c++
#include <iostream>
using namespace std;
int getMax(int arr[], int size, int &index) {
int max = arr[0];
index = 0;
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
index = i;
}
}
return max;
}
int main() {
int arr[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
int size = sizeof(arr) / sizeof(arr[0]);
int index;
int max = getMax(arr, size, index);
cout << "最大元素为:" << max << endl;
cout << "最大元素的下标为:" << index << endl;
return 0;
}
```
运行结果如下:
```
最大元素为:9
最大元素的下标为:5
```
希望能够帮到您!
相关问题
求一维数组的最大元素及其下标
好,针对您的问题,可以使用以下的代码实现:
```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
```
其中,`arr` 是输入的一维数组,`max_val` 是最大元素的值,`max_idx` 是最大元素的下标。可以通过调用这个函数来求解。
例如,假设我们有一个长度为 `5` 的数组 `arr`,如下所示:
```python
arr = [3, 5, 1, 7, 2]
```
那么我们可以调用 `find_max` 函数来求解最大元素及其下标,如下所示:
```python
max_val, max_idx = find_max(arr)
print("最大元素为:", max_val)
print("最大元素的下标为:", max_idx)
```
输出结果如下:
```
最大元素为: 7
最大元素的下标为: 3
```
希望这个代码可以帮到您!
求长度为10的一维数组元素最大值及其下标
可以使用以下 Python 代码来实现:
```python
import random
# 生成长度为10的随机数组
arr = [random.randint(1, 100) for _ in range(10)]
print("随机数组:", arr)
# 找到最大值及其下标
max_value = max(arr)
max_index = arr.index(max_value)
print("最大值:", max_value)
print("最大值下标:", max_index)
```
首先,我们使用 `random` 模块生成一个长度为10的随机数组。然后,我们使用 `max` 函数找到数组中的最大值,并使用 `index` 方法找到最大值的下标。最后,我们将最大值和下标打印出来。注意,Python 中的数组下标从0开始。
相关推荐
![](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)