c++ - 以相反顺序打印数组,意外输出 (c++)

标签 c++ arrays cin cout

我是编程新手,我现在的起始语言是 C++。我无法以相反的顺序打印一些数组。 在循环并递增变量后,每次递增输入一个值。

#include <iostream>
using namespace std;
int main(){

   int x=0;
   int a=0;
   int y=0;
   int arrayOne[40];
   int numberofTimes;
   int decrement;
   int operatorx;


cout<<"Enter first number: ";
cin>>numberofTimes;

for(int x; x<numberofTimes;x++){
    cout<<"Enter second number: ";
    cin>>y;
    arrayOne[x]=y;}
    decrement=numberofTimes*2;
while(decrement>numberofTimes){
    cout<<arrayOne[x]<<endl;
    x=x-1;
    decrement=decrement-1;
    }
   return 0;} 

最佳答案

实际上,您的代码只有两个真正的错误(但有很多“狡猾”的东西)!以下是更正/注释的工作版本:

#include <iostream>
using namespace std;
int main()
{
    int x;// = 0; // It is better to initialize this at the start of the FOR loop!
//  int a = 0; // You never use this variable!
    int y = 0;
    int arrayOne[40];
    int numberofTimes;
//  int decrement; // Better to declare and initialize this in one go (below)
//  int operatorx; // This is never used!
    cout << "Enter first number: ";
    cin >> numberofTimes;
//  for (int x; x < numberofTimes; x++) { // Here, you create a new variable, 'x' that hides the one you
    for (x = 0; x < numberofTimes; x++) { // have already defined; instead, use this to initialise x to zero
        cout << "Enter second number: ";
        cin >> y;
        arrayOne[x] = y;
    }
    int decrement = numberofTimes * 2; // Declare and initialise when needed!
    while (decrement > numberofTimes) {
        x = x - 1; // At the end of the first (FOR) loop, x will point to BEYOND the end of the array ...
        cout << arrayOne[x] << endl; // ... so you need to decrement it BEFORE accessing the elements!
    //  x = x - 1;
        decrement = decrement - 1;
    }
    return 0;
}

请随时询问进一步的解释!

关于c++ - 以相反顺序打印数组,意外输出 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58078238/

相关文章:

c++ - Qt 无法弄清楚如何在我的程序中线程化我的返回值

C++11 智能指针用例

c++ - Qt/C++ - 滚动和环绕菜单

c - 将指针传递给 C 中的二维指针数组

java - 将 double 组转换为 float 组

c++ - 在 C++ 中使用 cin

c++ - 无法理解 map 在 c++ 中的用法

javascript - ng-repeat 构建时间表

c++ - 在 QtCreator 中使用 cin

c++ if(cin>>input) 在 while 循环中不能正常工作