【问题描述】求一维数组中的最大值及最大值所在数组下标 【样例输入】 2030105040【样例输出】 t [3]=50
时间: 2023-11-13 10:07:08 浏览: 29
可以使用一个变量记录最大值和另一个变量记录最大值所在的数组下标,遍历一遍数组即可。以下是示例代码:
```python
arr = [2, 0, 3, 0, 1, 0, 5, 0, 4, 0]
max_val = arr[0]
max_index = 0
for i in range(1, len(arr)):
if arr[i] > max_val:
max_val = arr[i]
max_index = i
print("最大值为:", max_val)
print("最大值所在的数组下标为:t[", max_index, "]")
```
输出结果为:
```
最大值为: 5
最大值所在的数组下标为:t[ 6 ]
```
相关问题
【问题描述】求一维数组中的最大值及最大值所在数组下标 【样例输入】 20 30 10 50 40【样例输出】 t [3]=50
下面是一个C++的实现代码:
```c++
#include<iostream>
using namespace std;
int main()
{
int a[100],max=0,num=0,n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
if(max<a[i])//如果输入的数比max大,则更新max和num
{
max=a[i];
num=i;
}
}
cout<<"t ["<<num<<"]="<<max<<endl;//输出结果
return 0;
}
```
输入样例:
```
5
20 30 10 50 40
```
输出样例:
```
t [3]=50
```
求一维数组中的最大值及最大值所在数组下标
好的,可以使用以下算法来求解:
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
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)