如何产生随机数

来源:互联网 发布:有什么可靠的网络兼职 编辑:程序博客网 时间:2024/05/19 01:12
#include <stdio.h>#include <stdlib.h> int main() {  int c, n;   printf("Ten random numbers in [1,100]\n");   for (c = 1; c <= 10; c++) {    n = rand() % 100 + 1;    printf("%d\n", n);  }   return 0;

}

需要注意的一点是,如果仅仅用rand函数,你会发现每次运行,上述程序的输出都是一样的。为什么呢,因为rand每次运行只进行一次seeded,而种子的默认值为1。要避免这种情况,则要使用下面的程序。

#include <time.h>#include <stdlib.h>srand(time(NULL));int r = rand();
要记住,srand()只使用一次。如果

int a = 0;

int b;

for(; a<=10; a++)

{

srand(time(NULL));

b = rand();

}

则会发现b全部是一样的。原因是因为srand每秒钟只运行一次。

0 0