对于初学者,程序具有未定义的行为,因为变量 n 未初始化
int n;
所以这个声明
int a[n];
无效。此外,可变长度数组不是标准的 C++ 特性。而是使用标准类模板std::vector。
也在这个循环中
for(int i=n;i>=0;i--) {
cout<<a[i]<<" ";
}
您正在尝试访问索引为 n 的不存在元素。
此外,您没有反转数组。您正试图以相反的顺序输出一个数组。
注意在标头<algorithm>中声明了标准算法std::reverse和std::reverse_copy。
这是一个示例,使用您的方法的程序看起来如何
#include <iostream>
#include <vector>
int main()
{
size_t n = 0;
std::cout << "Enter the size of an array ";
std::cin >> n;
std::vector<int> v( n );
std::cout << "Enter " << n << " elements: ";
for ( auto &item : v ) std::cin >> item;
std::cout << "The array in the reverse order\n";
for ( size_t i = v.size(); i != 0; )
{
std::cout << v[--i] << ' ';
}
std::cout << '\n';
return 0;
}
程序输出可能看起来像
Enter the size of an array 10
Enter 10 elements: 0 1 2 3 4 5 6 7 8 9
The array in the reverse order
9 8 7 6 5 4 3 2 1 0
如果使用标准算法,那么您的程序可以如下所示
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
size_t n = 0;
std::cout << "Enter the size of an array ";
std::cin >> n;
std::vector<int> v( n );
std::cout << "Enter " << n << " elements: ";
std::copy_n( std::istream_iterator<int>( std::cin ), n, std::begin( v ) );
std::cout << "The array in the reverse order\n";
std::reverse_copy( std::begin( v ), std::end( v ),
std::ostream_iterator<int>( std::cout, " ") );
std::cout << '\n';
return 0;
}
程序输出可能与上面显示的方式相同
Enter the size of an array 10
Enter 10 elements: 0 1 2 3 4 5 6 7 8 9
The array in the reverse order
9 8 7 6 5 4 3 2 1 0