不使用种子C编程的随机数

时间:2012-10-15 08:18:35

标签: c random

有没有办法在不使用种子的情况下在C中生成随机数。

到目前为止,它仍然使用srand(time(NULL));这是种子。

#include <stdio.h>
#include <time.h>
#include <math.h> /* required for sqrt() */
#include <stdlib.h> /* required for rand() */

int gen_rand();   /* note these are declarations of functions */

void main()
{
   int number;
   srand (time(NULL)); /* everytime you run program, it will give you different result */

   number = gen_rand();

   printf("%d is the power of 2 of %.0lf\n", number, sqrt(number));
}

/* Function generates random number power 2 of 20 - 230 */
int gen_rand()
{
   int n;
   n = rand() % 211;  /* n is random number in range of 0 - 210 */
   n = n + 20; /* n is now in range of 20 - 230 */
   return(n*n); /* return n to the power of 2 */
}

4 个答案:

答案 0 :(得分:2)

是和否。 基本上有两种方法可以获得c中的远程随机数。

1)有一个带有种子的伪随机数生成器 - 这是一种算法,它使用聪明的算术运算符和可能的大量混合,置换,扭曲等内部变量产生一些数字序列。种子可以是隐式的(即总是为零,每次运行程序时,都会生成相同的序列)。或者它可以是显式的,其中种子可以在运行之间以某种方式改变。

2)使用外部数据源,在运行之间以某种方式发生变化。这可能来自计时器,环境变量(可能是程序ID),摄像机噪音,鼠标移动等。

1 + 2)使用外部噪声源作为伪随机数发生器的种子。

答案 1 :(得分:0)

所有基于非硬件的PRNG都需要某种形式的随机输入来对抗其确定性,因此总是需要种子。

你可以在linux下尝试滥用/dev/rand(但它也是PRNG),或者如果你有一个非常现代的英特尔CPU,他们的新digital RNG facilities会起作用。

答案 2 :(得分:0)

没有。如果您没有为自动数字生成器设定种子,它将确定性地运行并且每次都产生相同的数字。

答案 3 :(得分:0)

是。使用rand()函数生成随机数而不使用种子将为您提供相同的随机数集。

相关问题