печать массива в обратном порядке, неожиданные результаты (c ++) - PullRequest
1 голос
/ 24 сентября 2019

Я новичок в программировании, мой начальный язык сейчас 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;} 

1 Ответ

0 голосов
/ 24 сентября 2019

На самом деле, в вашем коде есть только две настоящие ошибки (но много «хитрых» вещей)!Ниже приведена исправленная / аннотированная рабочая версия:

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

Не стесняйтесь спрашивать дальнейшие объяснения!

...