c - 在 C 中随机用 2​​ 个整数填充数组

标签 c

我试图用 2 个值填充一个非常长的数组,每个索引应该以任意随机顺序包含 0 或 255。我怎么能这样做呢?我在那里找不到任何关于此的信息。

最佳答案

The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive (i.e., the mathematical range [0, RAND_MAX]).

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

所以你可以这样做:

#include<stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
  int v[10]; /* the 'very long' array */
  int i;

  srand(time(0)); /* random seed */

  /* populating */
  for (i = 0; i != sizeof(v)/sizeof(int); ++i)
    v[i] = (rand() & 1) * 255;

  for (i = 0; i != sizeof(v)/sizeof(int); ++i)
    printf("%d ", v[i]);
  putchar('\n');


  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall r.c
pi@raspberrypi:/tmp $ ./a.out
255 0 0 255 0 0 0 255 255 0 
pi@raspberrypi:/tmp $ ./a.out
0 255 0 0 0 255 0 255 255 0 
pi@raspberrypi:/tmp $ ./a.out
255 255 255 0 0 0 255 0 255 0 

关于c - 在 C 中随机用 2​​ 个整数填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55767668/

相关文章:

c - 这个语句在C中起什么作用?

c++ - 从使用 fmemopen() 打开的流中读取时的垃圾值

c - 错误地将 ASCII 输出为最接近的素数

c - 从链接列表保存到文件并将其加载回来

c++ - 通过宏替换展开循环无效

c++ - 在 Qt 中的 C++ 中添加 C 函数时出现问题

c - 将全局指针传递给函数

c - 如何确定字符串的长度(不使用 strlen())

c - 如何使用 WatCom 生成带有声明的段偏移量的 RAW BIN

c - C中的更多链表