【问题标题】:Populate and print array with random numbers using C使用 C 填充和打印带有随机数的数组
【发布时间】:2019-04-25 15:36:37
【问题描述】:

我正在尝试编写一个程序,该程序将使用 1 到 22 之间的数字填充 100 个元素的数组,然后在 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;

}

【问题讨论】:

  • rand() % ARY_SIZE --> rand() % 22 + 1
  • 你使用haveRand[]数组来避免已经使用过的数字,但是如果你需要用1到22的随机数填充100个数组元素,那么这将是不可能的.您的 do ... while 循环将永远运行。
  • 我建议用顺序值 1-22 填充一个数组,然后是 shuffling the array。它会快得多。
  • @MFisherKDX 你可以用随机数 [1, 22] 填充一个包含 100 个元素的数组而不会重复?
  • @Swordfish ...不。我想我对问题陈述感到困惑。 OP应该澄清她在问什么......这可能是不可能的。

标签: c arrays random


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    相关资源
    最近更新 更多