题解 | #数组元素反转#
数组元素反转
http://www.nowcoder.com/practice/8c9793ae96974a9ebb153d90ef31d357
//元素对调方法 第一个值与最后一个值对掉 第二个值与倒数第二个值对掉需要中间变量换值
#include using namespace std;
int main() {
int arr[6] = { 0 };
int len = sizeof(arr) / sizeof(int);
for (int i = 0; i < len; i++) {
cin >> arr[i];
}
cout << "[";
for (int i = 0; i < len; i++) {
if (i == len - 1) {
cout << arr[i] << "]" << endl;
break;
}
cout << arr[i] << ", ";
}
// write your code here......
int l=0,r=5,temp=0;//建立中间变量temp
while(l<r){
temp=arr[l];
arr[l]=arr[r];
arr[r]=temp;
l++;
r--;
}
cout << "[";
for (int i = 0; i < len; i++) {
if (i == len - 1) {
cout << arr[i] << "]" << endl;
break;
}
cout << arr[i] << ", ";
}
return 0;
}