[英]Populate and print array with random numbers using C
我正在嘗試編寫一個程序,該程序將填充100個具有1到22之間數字的元素的數組,然后在20 x 5的表中打印該數組。 我能夠填充並打印該數組,但只能使其與數字1-100一起使用,如何更改為僅對數字1-22進行處理?
#include <stdio.h>
#include <stdlib.h>
#define ARY_SIZE 100
void random (int randNos[]);
void printArray (int data[], int size, int lineSize);
int main(void)
{
int randNos [ARY_SIZE];
random(randNos);
printArray(randNos, ARY_SIZE, 20);
return 0;
}
void random (int randNos[])
{
int oneRandNo;
int haveRand[ARY_SIZE] = {0};
for (int i = 0; i < ARY_SIZE; i++)
{
do
{
oneRandNo = rand() % ARY_SIZE;
} while (haveRand[oneRandNo] == 1);
haveRand[oneRandNo] = 1;
randNos[i] = oneRandNo;
}
return;
}
void printArray (int data[], int size, int lineSize)
{
int numPrinted = 0;
printf("\n");
for (int i = 0; i < size; i++)
{
numPrinted++;
printf("%2d ", data[i]);
if (numPrinted >= lineSize)
{
printf("\n");
numPrinted = 0;
}
}
printf("\n");
return;
}
@Sarah只需包含time.h
頭文件(來自標准庫),然后按如下所示重寫您的隨機函數:
void Random(int RandNos[])
{
/*
Since your random numbers are between 1 and 22, they correspond to the remainder of
unsigned integers divided by 22 (which lie between 0 and 21) plus 1, to have the
desired range of numbers.
*/
int oneRandNo;
// Here, we seed the random generator in order to make the random number truly "random".
srand((unsigned)time(NULL));
for(int i=0; i < ARY_SIZE; i++)
{
oneRandNo = ((unsigned )random() % 22 + 1);
randNos[i] = oneRandNo; // We record the generate random number
}
}
注意:要求您包括time.h
以便使用time()
函數。 如果您在Linux或Mac OSX下工作,則可以通過在終端中鍵入man 3 time
命令來輕松訪問文檔,以找到有關此功能的更多信息。
同樣,將函數命名為random
將與標准庫的命名沖突。 這就是為什么我改用Random
原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.