【问题标题】:why does rand keep producing the same value every time in c++? [duplicate]为什么 rand 在 C++ 中每次都产生相同的值? [复制]
【发布时间】:2016-04-20 16:43:11
【问题描述】:

我有密码

char a = 97 + rand() % 26;
char b = 97 + rand() % 26;
char c = 97 + rand() % 26;
char d = 97 + rand() % 26;
char e = 97 + rand() % 26;
char f = 97 + rand() % 26;

在我的程序中,在主文件中,当我执行文件时,我每次都会得到序列 lvqdyo,而我认为它每次都会随机化。任何见解都将不胜感激,无论它是否是答案。

【问题讨论】:

    标签: c++ random


    【解决方案1】:

    首先使用srand() 初始化随机种子。 当前时间也可以用来做同样的事情:

    #include <cstdlib> // this is where srand() is defined
    #include <ctime> // this is where time() is defined
    srand (time(NULL));
    char a = 97 + rand() % 26;
    ...
    

    请参考this

    这样的随机种子确保每次对rand() 的后续调用都会产生一个随机数。

    【讨论】:

      【解决方案2】:

      要使用rand(),你必须先播种,见下面的例子

      /* rand example: guess the number */
      #include <stdio.h>      /* printf, scanf, puts, NULL */
      #include <stdlib.h>     /* srand, rand */
      #include <time.h>       /* time */
      
      int main ()
      {
        int iSecret, iGuess;
      
        /* initialize random seed: */
        srand (time(NULL));
      
        /* generate secret number between 1 and 10: */
        iSecret = rand() % 10 + 1;
      
        do {
          printf ("Guess the number (1 to 10): ");
          scanf ("%d",&iGuess);
          if (iSecret<iGuess) puts ("The secret number is lower");
          else if (iSecret>iGuess) puts ("The secret number is higher");
        } while (iSecret!=iGuess);
      
        puts ("Congratulations!");
        return 0;
      }
      

      srand(time(NULL)) 确保种子正在启动,以便rand 可以正常工作

      阅读来源: CPP - Rand()

      【讨论】:

        【解决方案3】:

        这是因为Random 不是真正随机的。它是一个相当 pseudo 随机的,取决于 seed

        对于一个随机种子,你有一个精确集随机序列。这就是为什么每次运行程序都会得到相同结果的原因,因为一旦编译,随机种子就不会改变

        为了让您的应用程序在每次运行时都具有类似随机的行为,请考虑使用时间信息作为随机种子:

        #include <cstdlib.h>
        #include <time.h>
        
        ....
        srand (time(NULL)); //somewhere in the initialization    
        

        time(NULL) 是随机种子,它将根据您运行应用程序的系统时间而改变。然后你可以每次使用你的rand() 和不同的随机种子:

        //somewhere else after initialization
        char a = 97 + rand() % 26;
        char b = 97 + rand() % 26;
        char c = 97 + rand() % 26;
        char d = 97 + rand() % 26;
        char e = 97 + rand() % 26;
        char f = 97 + rand() % 26;
        

        【讨论】:

          猜你喜欢
          • 2012-03-16
          • 2016-03-29
          • 1970-01-01
          • 2020-06-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-09
          相关资源
          最近更新 更多