C语言随机数生成

    xiaoxiao2022-07-12  164

    伪随机数

    种子在每次启动计算机时是随机的,但是一旦计算机启动以后它就不再变化了;也就是说,每次启动计算机以后,种子就是定值了,所以根据公式推算出来的结果(也就是生成的随机数)就是固定的

    #include <stdio.h> #include <stdlib.h> int main(){ int a = rand(); printf("%d\n",a); return 0; }

    解决方法

    它需要一个 unsigned int 类型的参数。在实际开发中,我们可以用时间作为参数,只要每次播种的时间不同,那么生成的种子就不同,最终的随机数也就不同。

    #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int a; srand((unsigned)time(NULL)); a = rand(); printf("%d\n", a); return 0; }

    连续随机数的生成

    有时候我们需要一组随机数(多个随机数),该怎么生成呢?很容易想到的一种解决方案是使用循环,每次循环都重新播种,请看下面的代码:

    #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int a, i; srand((unsigned)time(NULL)); //使用for循环生成10个随机数 for (i = 0; i < 10; i++) { a = rand()00; printf("%d ", a); } return 0; }
    最新回复(0)