c - 使用 C 使用随机数填充和打印数组

标签 c arrays random

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

最佳答案

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

关于c - 使用 C 使用随机数填充和打印数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53439645/

相关文章:

java - 指向作为 JNA 方法参数的结构数组的指针

c - 在两个进程之间共享信号量数组 | Linux C

Java 7 : ThreadLocalRandom generating the same random numbers

php - 如何在没有任何循环php的情况下从数组中随机获取项目

java - 在浮点和整数数组中查找最大元素索引的常用方法

php - 来自文本种子的随机数

random - Math.random() 的大 O 估计?

c - 如何在 Join Five 游戏中找到所有可能的 5 点对齐

c - C 中的字符串操作?

c# - 将 LPWSTR * 字符串指针数组转换为 C#