[英]Passing 2D array Random Number Generator into main with C++
嗨,大家好,我是C ++的新手,我想知道你們是否可以幫助我。 現在,我只是在看書,而老師告訴我要這樣做,因此某些內容可能看起來有所不同。
我想做的是讓我的void隨機生成器將數字放入2D數組中,然后進入main。 然后,我將其傳遞到我的顯示功能中,但是由於某種原因,我無法使其正常運行。 你們能幫我嗎?
編輯:好的,我想這與我的隨機數生成器有關,不是將數字放入數組中,但不確定為什么。 由於我的數字生成器有效,因此可以找到一維數組。
#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;
}
每次您在種群()中輸入第二個for循環時,您似乎都在為隨機數生成器播種。 您應該只在開始附近的程序中為隨機數生成器播種一次。
嘗試從人口()中刪除您的種子行,而不是使用
srand(time(NULL));
在main()的開頭
嗯,我知道了問題所在。 我一直誤以為是一個巨大的列,而不是將其分為行和列。
我必須在a [i] [J]部分后面留一個小空間,以便可以將其分為行和列。
cout << setw(4) << a[a][J] << " ";
That_Knight_Guy感謝您的建議。 現在,我的生成器終於發出了隨機數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.