编写程序在数组中将10个元素中值最大的一个找出并与第一个元素交换
时间: 2024-01-22 11:18:27 浏览: 39
以下是一个示例 Python 代码,可以实现这个功能:
```python
# 初始化数组
arr = [5, 2, 8, 3, 9, 1, 6, 4, 7, 10]
# 找到最大值的索引
max_index = 0
for i in range(1, len(arr)):
if arr[i] > arr[max_index]:
max_index = i
# 交换最大值与第一个元素的位置
arr[0], arr[max_index] = arr[max_index], arr[0]
# 输出结果
print(arr)
```
输出结果为:
```
[10, 2, 8, 3, 9, 1, 6, 4, 7, 5]
```
其中,`max_index` 变量用于存储数组中最大值的索引,`for` 循环用于遍历数组并找到最大值的索引,最后使用 Python 的交换变量值的语法 `a, b = b, a` 将最大值与第一个元素交换位置。
相关问题
用c++写出编写程序在数组中将10个元素中值最大的一个找出并与第一个元素交换
下面是用C++实现的程序,在10个元素中找出最大值并与第一个元素交换的过程。
```c++
#include <iostream>
using namespace std;
int main() {
int arr[10] = {5, 8, 3, 9, 2, 7, 1, 6, 4, 10}; // 定义一个含有10个元素的数组,初始值已给出
int max_index = 0; // 最大值的索引,初始值设为第一个元素
int max_val = arr[0]; // 最大值,初始值设为第一个元素
// 找出最大值的索引和数值
for (int i = 1; i < 10; i++) {
if (arr[i] > max_val) {
max_val = arr[i];
max_index = i;
}
}
// 将最大值与第一个元素交换
int temp = arr[0];
arr[0] = max_val;
arr[max_index] = temp;
// 输出交换后的数组
for (int i = 0; i < 10; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
10 8 3 9 2 7 1 6 4 5
```
可以看到,程序成功地将最大值10与第一个元素5进行了交换。
用c++数组编程写出编写程序在数组中将10个元素中值最大的一个找出并与第一个元素交换
以下是用C++数组编写的程序,可以找出给定数组中的最大值,并将其与第一个元素交换。
```c++
#include <iostream>
using namespace std;
int main() {
int arr[10]; // 声明一个长度为10的整型数组
int maxIndex = 0; // 最大值的下标初始化为0
cout << "请输入10个整数:" << endl;
for (int i = 0; i < 10; i++) {
cin >> arr[i]; // 通过循环读取用户输入的10个整数
if (arr[i] > arr[maxIndex]) {
maxIndex = i; // 更新最大值的下标
}
}
// 输出原始数组
cout << "原始数组:" << endl;
for (int i = 0; i < 10; i++) {
cout << arr[i] << " ";
}
cout << endl;
// 将最大值与第一个元素交换
int temp = arr[0];
arr[0] = arr[maxIndex];
arr[maxIndex] = temp;
// 输出交换后的数组
cout << "交换后的数组:" << endl;
for (int i = 0; i < 10; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
例子输出:
```
请输入10个整数:
3 7 1 9 4 6 8 2 5 0
原始数组:
3 7 1 9 4 6 8 2 5 0
交换后的数组:
9 7 1 3 4 6 8 2 5 0
```