简体   繁体   中英

Passing 2D array Random Number Generator into main with C++

Hi guys I'm very new to C++ and was wondering if you guys could help me. Right now I'm just going by the book and what the teacher told me to do so some of the stuff might look different.

What I want to do is have my void random generator put numbers into my 2D array and then it goes into main. Then I have it pass through into my display function but for some reason I can't get it work right. Can you guys help me out?

edit: Ok I figured that it has something to do with my random number generator not putting the numbers into the array but not sure why. Since my number generator works find with 1D Array.

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

using namespace std;

//Globral Varaibles Must be on top 
const int max = 100;
const int min = 1;
const int COL = 4;
const int Rows = 3;

//Functions
void Population(int Array[][COL], int size);
void Show(const int Array[][COL], int max);

int main()
{
     int a[3][4];
     Population(a, Rows);
     Show(a, Rows);
}

void Population( int Array[][COL], int size)
{
    for (int index = 0; index < Rows; index++)
    {
        for (int Count = 0; Count < COL; Count++)
        {
               unsigned seed = time(0);
               Array[index][Count] = (rand() % (max - min + 1)) + min;
        }
    }
}

void Show(const int a[][COL], int Rows)
{
    for (int i = 0; i < Rows; i++)
    {
        for (int J = 0; J < COL; J++)
        {
            cout << setw(4) << a[i][J] << endl;
        }
    }
    cout << endl;
    cout << endl;
}

You seem to be seeding your random number generator every time you enter your second for loop in population(). You should only seed a random number generator once in a program, near the beginning.

Try removing your seed line from population() and instead using

srand(time(NULL));

at the beginning of your main()

AH, I figured out the problem. I had been mistaking what was being showing as one giant column instead of it being divided into rows and columns.

I had to have a small space after the a[i][J] part so that it could be divided into rows and columns.

cout << setw(4) << a[a][J] << " ";

That_Knight_Guy thanks for the suggestion. Now my generator finally puts out random numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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