这段代码是用C++编写的,它实现了将一个整数数组逆置的功能。具体来说,它首先创建一个长度为5的整数数组,并输出其原始顺序。然后,通过使用两个指针(start和end),它实现了数组的逆置。最后,它再次遍历数组,并输出逆置后的结果。
以下是代码的注释解释:
#include <iostream> // 包含输入输出流库
using namespace std;
int main() { // 主函数
// 1. 创建数组
int arr[5] = { 1, 3, 2, 5, 4 };
cout << "数组逆置前:" << endl;
for (int i = 0; i < 5; i++) {
cout << arr[i] << endl;
}
// 2. 实现逆置
// 2.1 记录起始下标位置
// 2.2 记录结束下标位置
// 2.3 起始下标与结束下标的元素互换
// 2.4 起始位置++ 结束位置--
// 2.5 循环执行2.1操作,直到起始位置>=结束位置
int start = 0; // 起始下标
int end = sizeof(arr) / sizeof(arr[0]) - 1; // 结束下标
while (start < end) {
// 实现元素互换
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// 下标更新
start++;
end--;
}
// 3. 打印逆置后的数组
cout << "数组元素逆罩后:" << endl;
for (int i = 0; i < 5; i++) {
cout << arr[i] << endl;
}
return 0; // 主函数返回0,表示程序正常结束
}
这段代码的输出结果如下:
数组逆置前:
1
3
2
5
4
数组元素逆罩后:
4
2
3
1
5