对一维数组a[N]的处理: (1)实现数组a[N]的输入和输出; (2)找出数组a[N]的最大值或最小值; (3)对数组a[N]进行倒置; (4)求数组a[N]所有元素的和及平均值; 并输出结果
时间: 2023-12-16 07:02:45 浏览: 33
(1) 数组a[N]的输入和输出可以通过以下代码实现:
```cpp
#include <iostream>
int main() {
const int N = 5; // 数组的大小
int a[N]; // 定义数组
// 输入数组元素
std::cout << "请输入" << N << "个整数:" << std::endl;
for (int i = 0; i < N; i++) {
std::cin >> a[i];
}
// 输出数组元素
std::cout << "数组元素为:";
for (int i = 0; i < N; i++) {
std::cout << a[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
(2) 找出数组a[N]的最大值或最小值可以通过以下代码实现:
```cpp
#include <iostream>
int main() {
const int N = 5; // 数组的大小
int a[N]; // 定义数组
// 输入数组元素
std::cout << "请输入" << N << "个整数:" << std::endl;
for (int i = 0; i < N; i++) {
std::cin >> a[i];
}
// 找出最大值和最小值
int max = a[0];
int min = a[0];
for (int i = 1; i < N; i++) {
if (a[i] > max) {
max = a[i];
}
if (a[i] < min) {
min = a[i];
}
}
std::cout << "最大值为:" << max << std::endl;
std::cout << "最小值为:" << min << std::endl;
return 0;
}
```
(3) 对数组a[N]进行倒置可以通过以下代码实现:
```cpp
#include <iostream>
int main() {
const int N = 5; // 数组的大小
int a[N]; // 定义数组
// 输入数组元素
std::cout << "请输入" << N << "个整数:" << std::endl;
for (int i = 0; i < N; i++) {
std::cin >> a[i];
}
// 倒置数组
for (int i = 0; i < N/2; i++) {
int temp = a[i];
a[i] = a[N-1-i];
a[N-1-i] = temp;
}
// 输出倒置后的数组
std::cout << "倒置后的数组为:";
for (int i = 0; i < N; i++) {
std::cout << a[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
(4) 求数组a[N]所有元素的和及平均值可以通过以下代码实现:
```cpp
#include <iostream>
int main() {
const int N = 5; // 数组的大小
int a[N]; // 定义数组
// 输入数组元素
std::cout << "请输入" << N << "个整数:" << std::endl;
for (int i = 0; i < N; i++) {
std::cin >> a[i];
}
// 计算数组元素的和
int sum = 0;
for (int i = 0; i < N; i++) {
sum += a[i];
}
// 计算数组元素的平均值
double average = static_cast<double>(sum) / N;
std::cout << "数组元素的和为:" << sum << std::endl;
std::cout << "数组元素的平均值为:" << average << std::endl;
return 0;
}
```
以上是使用 C++ 语言实现的对一维数组a[N]的处理。请注意,输入的数组大小为5,你可以根据实际需求进行修改。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)