1.对于给定的元素的逆置:
#include <iostream>
using namespace std;
int main(){
int arr[5]={1,2,3,4,5}; //数组元素给定
int start=0; //记录数组的第一个位置的标
int end=sizeof(arr)/sizeof(arr[0]) - 1 ; //记录数组的最后一个位置的数
int count=end;
int temp=arr[start]; //申请一个空间,做中转
while(start<end){
temp=arr[start];
arr[start]=arr[end];
arr[end]=temp;
start++;
end--;
}
for(int i=0; i<=count;i++){
cout<<arr[i]<<" ";
}
}
2.对于随机输入一维数组的数据:
#include <iostream>
using namespace std;
int main(){
//输入数据:
int num=0; //接受用户输入的数据
int arr[100]; // 定义一个一维数组,存储数据
int count = 0; //统计输入的数据的个数
//输入元素
cout<<"请输入你要输入的数据(输入-1表示结束):"<<endl;
cin>>num;
int i=0;
while(num!=-1){
arr[i]=num;
i++;
cin>>num;
count++;
}
//输出逆置前的元素
cout <<"您输入的数据是:";
for(int i=0; i<=count-1; i++){
cout <<arr[i]<<" ";
}
cout << endl;
//元素的逆置
int start=0; //用于标记开始时的第一个元素的下标
int end=count -1; //用于标记最后一个元素的下标
int temp; //定义一个新的变量,用于元素的交换
while(start<end){
temp=arr[start];
arr[start]=arr[end];
arr[end]=temp;
start++;
end--;
}
//输出逆置后的元素
cout<<"逆置后的元素顺序为:"<<endl;
for(int i=0; i<=count-1; i++){
cout <<arr[i]<<" ";
}
}