繁体   English   中英

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

[英]printing array in a reverse order, unexpected outputs (c++)

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

#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;
}

随时要求进一步的解释!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM