如何在C随机数生成器的工作? [英] How does the random number generator work in C?

查看:106
本文介绍了如何在C随机数生成器的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成0和40(含)之间的随机数。
因此,code,我实现是这样的 -

I'm trying to generate random number between 0 and 40(inclusive). So the code I Implemented is this-

 y=rand()%41;

但是每次我点击编译并运行命中。它输出相同的随机数。
至于中说比如我在一个循环中运行此。

However everytime I click compile and hit Run. It outputs the same random numbers. As in say for instance I ran this in a loop.

for(i=0;i<4;i++)
{
     y=rand()%41;
     printf("%d ",y);
}

每一个时间内,输出是相同的4个数字。它总是输出14,2,等等等等在终端上。不管是什么。

Every single time, the output is the same 4 numbers. It always outputs 14,2,etc etc on the terminal. No matter what.

所以我的第一个问题是,为什么会出现这种情况?

So my first question is, why is this happening?

和第二,如何做C中的随机数生成器的工作?

and Secondly, how does the random number generator work in C?

我想既然我有time.h中库,通过一些标准算法使用该系统时所产生的数字。而且,由于系统时间不断变化,即产生也应该改变我每次运行程序时的数字。

I thought since I include time.h library, the numbers are generated through some standard algorithm using the system time. And since the system time is continuously changing, the numbers that are generated should also change every time I run the program.

推荐答案

兰特()只产生伪随机数。这意味着每次你运行你code时,你会得到完全相同的数字序列。

rand() generates only pseudorandom numbers. This means that every time you run your code you will get exactly the same sequence of numbers.

考虑使用

srand(time(NULL))

要每次都遇到不同的号码。事实上可能实施兰特

to get every time different numbers. In fact a possible implementation for rand is

next = next * 1103515245 + 12345;
return (UINT32)(next>>16) & RAND_MAX;

其中,接下来定义为

static UINT32 next = 1;

调用函数srand()具有改变接下来,从而改变了下一个初始值的影响珍惜你作为结果。

Calling srand() has the effect of changing the initial value of next, thus changing the "next" value you get as result.

这篇关于如何在C随机数生成器的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆