c - 在C中生成不相等的随机数

标签 c random numbers

我编写了一个生成 4 个随机数字的程序,它应该像这样出现在屏幕上:从 0000 到 9999(当然不一定按升序排列!)。

问题是我遇到了彼此相等的数字。我该如何解决?我只想生成 0000 到 9999 范围内的 10.000 个数字,但不按任何顺序:只是“随机”。

这是我到目前为止写的:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#define SIZE 10000

int main(){

    srand(time(NULL));

    int a[SIZE], b[SIZE], c[SIZE], d[SIZE], i;
    FILE *fd = fopen("combinations_rand.txt", "w");
    assert(fd);

    for(i=0; i<SIZE; i++){      
        a[i] = rand()%10; //array of first digits
        b[i] = rand()%10; //array of second digits, etc...
        c[i] = rand()%10;
        d[i] = rand()%10;
        fprintf(fd, "%d%d%d%d\n", a[i], b[i], c[i], d[i]);
     }
     fclose(fd);
}

最佳答案

取一个长度为 10000 的数组,并将 0 到 9999 的元素存储在其中。 然后打乱数组Shuffle array in C .

然后在需要时用前导零打印答案Printing leading 0's in C?

关于c - 在C中生成不相等的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33792524/

相关文章:

ios - 如果我在 5 点或 5 :01, 调用 arc4random_uniform(6),我会得到相同的数字吗?

c++ - while循环c++中的非法指令

javascript - 为什么这个数字会增加一个?

php: 只有数字哈希?

c - 了解已编译目标文件中 C 函数的大小

mysql 为 rand 设置种子

random - 如何在JMeter中的页面请求之间添加不同的时间延迟?

c - 一个将转换数字基数和非法输入错误的函数

c - 没有双向链表

c - 在线程内实现计时器的最佳方法是什么?