C++ 我想以相反的顺序打印数组,我试图为所附图片中显示的相同内容编写代码,但我不理解为什么显示0?
这是我试过的代码C++ 我想以相反的顺序打印数组,我试图为所附图片中显示的相同内容编写代码,但我不理解为什么显示0?,c++,arrays,C++,Arrays,这是我试过的代码 int main(){ int n; cout<<"Type the number of elements\n"; cin>>n; cout<<"Type the integars"; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } cout<<"This is the reversed arr
int main(){
int n;
cout<<"Type the number of elements\n";
cin>>n;
cout<<"Type the integars";
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<"This is the reversed array ";
for(int i=n;i>=0;i--){
cout<<arr[i]<<" ";
}
return 0;
}
intmain(){
int n;
coutn;
cout问题是反向数组从n
开始,而arr[n]
无效,因为数组从0开始
for(int i=n-1;i>=0;i--){
cout解决方案:使用i=n-1打印
int main(){
int n;
cout<<"Type the number of elements\n";
cin>>n;
cout<<"Type the integars";
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<"This is the reversed array ";
for(int i=n-1;i>=0;i--){
cout<<arr[i]<<" ";
}
return 0;
}
intmain(){
int n;
coutn;
cout数组从零开始计数到n(n是目标大小值),因此需要忽略该零值,并在零经过迭代后开始打印
比如:
counter = target -1
您的数组大小为5,但您正在访问6个元素,而不是5个。也就是说,当数组只有4…0(总共5个)元素时,您正在访问元素5…0(总共6个)
以n-1开始第二个for循环,这将解决您的问题。也就是说,(for(int i=n-1;i>=0;i--)而不是(for(int i=n;i>=0;i--))打印数组的背面时,请确保记住元素的位置总是少一个。
因此,必须从n-1开始。打印“0”,因为它是该位置的垃圾值,可能是任何数字或值
int main(){
int n;
cout<<"Type the number of elements\n";
cin>>n;
cout<<"Type the integars";
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<"This is the reversed array ";
// When printing the reverse of array make sure you remember the position of elements is always one less.
// So you have to start with n-1. '0' is getting printed because it is the garbage value at that position it could have been any number or value.
for(int i=n-1;i>=0;i--){
cout<<arr[i]<<" ";
}
return 0;
}
intmain(){
int n;
coutn;
可以在第一个for循环中读取n个整数,但在第二个for循环中尝试打印n+1个整数。在第二个for循环中从int i=n-1开始,就可以了。对于长度为5的数组,最后的循环n=5,4,3,2,1,0-6次迭代。arr[5]
已超出范围。请从int i=n-1
开始,即使您只修复了一个错误,但您的代码实际上无效。请查看std::vector
。打印反向数组时,将起点更改为int i=n-1