使用C填充并打印具有随机数的数组

时间:2018-11-23 01:21:40

标签: c arrays random

我正在尝试编写一个程序,该程序将填充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;

}

1 个答案:

答案 0 :(得分:0)

@Sarah只需添加time.h头文件(来自标准库),然后重写您的 random 函数,如下所示:

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的原因。