[英]seeding and random number generating
I am trying to understand the random-generating-function in c. 我试图理解c中的随机生成函数。
For what I read the random number returned by the function is dependent on its initial value, called a seed that remains the same for each run of a program. 对于我读到的内容,函数返回的随机数取决于其初始值,称为种子,对于程序的每次运行都保持相同。 This means that the sequence of random numbers that is generated by the program will be exactly the same on each run of the program.
这意味着程序生成的随机数序列在程序的每次运行中都是完全相同的。
So this is solved by using another function- srand(seed) - which will use a different seed value on every run, causing a different set of random values every run. 所以这是通过使用另一个函数 - srand(种子)来解决的 - 它将在每次运行时使用不同的种子值,每次运行时会导致一组不同的随机值。 And to seed this random number generator with a arbitrary value the System clock could be used.
并且可以使用任意值对该随机数生成器进行播种,可以使用系统时钟。 So in summary: the time is used as a seed value.
总而言之:时间用作种子值。
So after implementing the srand(seed)-function the random number generating reallt worked fine, BUT - what i do not understand is that the seed value is always the same. 因此,在实现srand(种子)函数之后,生成reallt的随机数工作正常,但是 - 我不明白的是种子值总是相同的。 I thought the whole idea about seeding the random number generator was to use a new seed-value every time the program executes.
我认为关于播种随机数生成器的整个想法是每次程序执行时都使用新的种子值。 But in the console-window in Eclipse the seed-value seems to be the same everytime, ie 4071056, 4071056, 4071056, 4071056, 4071056, 4071056
但是在Eclipse的控制台窗口中,种子值似乎每次都是相同的,即4071056,4071056,4071056,4071056,4071056,4701056
and the random numbers generated for instance: 1,6,5,5,1,4 以及例如生成的随机数:1,6,5,5,1,4
Got the information from http://www.cprogramming.com/tutorial/random.html 从http://www.cprogramming.com/tutorial/random.html获取信息
EDIT: *Think I understand it now. 编辑: *我想我现在明白了。 In java it would be a missmatch error between int and void,
在java中,它将是int和void之间的错配,
int t = srand(time(NULL));
printf("seed value: %d \n", t);
int rand_nmbr = (rand() % 6 + 1);
printf("dice face: %d ", rand_nmbr);
srand
doesn't return a value; srand
没有返回值; its prototype is 它的原型是
void srand(unsigned int seed);
assigning the (non-existent) result of srand
to t
is a coding error; 将
srand
的(不存在的)结果分配给t
是编码错误; you're just printing out garbage. 你只是打印出垃圾。
If you want to see the actual value of the seed use 如果要查看种子使用的实际值
time_t t;
time(&t);
srand(t);
srand()
function is of void
type which returns nothing. srand()
函数是void
类型,不返回任何内容。 Your compiler should give error for this 您的编译器应该为此提供错误
[Error] void value not ignored as it ought to be
calling a void
function by assigning it to a variable is wrong. 通过将
void
函数赋值给变量来调用void
函数是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.