我试图用 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/