DannyD
DannyD

Reputation: 2881

I can't figure out why my random numbers I'm generating are not storing correctly

I'm making a program that generates a random x and y point for an amount of numbers that is entered by someone. For some reason my random numbers aren't being stored right in the array. I output the array while in the loop that's generating the points and at the end in a for loop and the y coordinates are not the same:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {


srand((unsigned)time(0)); 

int mounds =0;


//prompt for number of mounds, uncertainty, and number of sites
cout <<"Please enter the number of mounds at the site: ";
cin >> mounds;


//declaration of an array that will hold the x and y for each mound
int moundArray [mounds][1];


    for(int i =0; i < mounds; i++)
    {
        //generate a random x
        moundArray [i][0] = rand()%1331;
        cout <<"You just generated an x of: " << moundArray [i][0] << endl;
        //sleep(1);


        //generate a random y
        moundArray [i][1] = rand()%1743;
        cout <<"You just generated a y of: " << moundArray [i][1] << endl;
        //sleep(1);

    }



    //for loop to display my results
    for(int j =0; j < mounds; j++)
    {

        cout <<"random x: " << moundArray [j][0] << endl;
        cout <<"random y: " << moundArray [j][1] << endl;
    }



return 0;
}

Upvotes: 0

Views: 99

Answers (2)

Logan Nichols
Logan Nichols

Reputation: 397

I'm surprised you aren't crashing on execution. This line right here should be your problem:

int moundArray [mounds][1];

if the second index only has a size of [1], then element [0] is the only valid element to access. try increasing that to 2.

Upvotes: 2

A E
A E

Reputation: 586

int moundArray [mounds][1];

mounds and 1 represent the number of elements, not the last index in the array.

cout <<"You just generated a y of: " << moundArray [i][1] << endl;

Above you are using 1 as the index in the second field which would imply that the array has at least two (2) elements in that dimension.

Upvotes: 2

Related Questions