C++随机数生成函数rand()陷阱

看下面代码,用于生成随机数

1
2
3
4
5
6
7
int main(){
    cout<<"rand() traps by Sparkles."<<endl;<br>    int N = 10;
    for (int i = 0; i < N; ++i)
        cout<< rand()%n;
    getchar();
    return 0;
}

结果如下:

  1. rand() traps by Sparkles.
  2. 1740948824

似乎并没有什么异常,但是,如果多次运行程序,会发现,每次生成的结果都是一样的。

这个问题网上解释很充分,另见:http://www.cplusplus.com/reference/cstdlib/rand/ 

rand
int rand (void);
Generate random number

Returns a pseudo-random integral number in the range between 0 and RAND_MAX.

This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.

上文提到,rand()算法是由一个seed来生成随机数的,可以通过srand()来定义这个seed。而一开始的例子中,并未调到srand(),所以rand()默认将1作为seed来生成随机数。(狗屎的节奏哇)

下面是通过设置seed来生成随机数,可以看到,当seed不同的时候,随机数结果会变化,最后一种将seed设置成time(0)是网上比较通用的做法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main(){
    int N = 10;
    cout<<"rand() traps by Sparkles."<<endl;
    cout<<"Set seed as 1\t\t\t";
    srand(1);
    for (int i = 0; i < N; ++i)
        cout<< rand()%N;
     
    cout<<endl<<"Set seed as 2\t\t\t";
    srand(2);
    for (int i = 0; i < N; ++i)
        cout<< rand()%N;
 
    cout<<endl<<"Set seed as current time\t";
    srand(time(0));
    for (int i = 0; i < N; ++i)
        cout<< rand()%N;
    getchar();
    return 0;
}
  1. rand() traps by Sparkles.
  2. Set seed as 1 1740948824
  3. Set seed as 2 5685400156
  4. Set seed as current time 1907157566

  

 

C++随机数生成函数rand()陷阱,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。