(程序设计)编写程序,按照指定长度生成动态数组,用随机数对数组元素进行赋值,然后逆置该数组元素。例如,数组A的初值为{6, 3, 7, 8, 2},逆置后的值为{2, 8, 7, 3, 6}。要求:输出逆置前、后的数组元素序列。
时间: 2023-11-27 07:49:20 浏览: 87
下面是一个C++的示例代码:
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
// 生成随机种子
srand(time(NULL));
int n;
cout << "请输入数组长度:";
cin >> n;
int *arr = new int[n];
cout << "原始数组:";
for (int i = 0; i < n; i++) {
arr[i] = rand() % 100; // 生成0-99之间的随机数
cout << arr[i] << " ";
}
// 逆置数组元素
for (int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}
cout << "\n逆置后的数组:";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
delete[] arr; // 释放动态数组内存
return 0;
}
```
运行示例:
```
请输入数组长度:5
原始数组:19 26 10 55 49
逆置后的数组:49 55 10 26 19
```
注意,在动态数组使用完毕后,需要使用 `delete[]` 关键字释放内存,避免内存泄漏。
阅读全文