【问题标题】:Rand() command generates the same numbers every time [duplicate]Rand()命令每次生成相同的数字[重复]
【发布时间】:2021-11-03 01:24:00
【问题描述】:

我每次都在循环中使用 rand() 生成随机数,直到循环完成,但它总是给出相同的数字,我做错了什么?

 bool PlayGame(int Difficulty, bool bComplete)
{

    
    int CodeA =rand() % Difficulty + Difficulty;
    int CodeB =rand() % Difficulty + Difficulty;
    int CodeC =rand() % Difficulty + Difficulty;
   

【问题讨论】:

  • 您需要在int main()开始时为随机数生成器播种1次
  • 您需要为随机生成器播种:另请参阅:stackoverflow.com/questions/69056209/…。对于 C++,请考虑使用 头文件中的函数(rand 随机性较小,“c”比“c++”更多)
  • 只是好奇:在过去的几天里,有很多类似的问题。是否有课程促使人们编写使用随机数的代码?
  • @PeteBecker 是的随机数和 c 样式数组 ;)
  • 感谢大家的帮助!我真的是新人哈哈

标签: c++


【解决方案1】:

您可以通过在开始时设置srand(time(0)); 来使用当前时间作为随机生成器的种子

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
// Driver program
int main(void)
{
    // This program will create different sequence of
    // random numbers on every program run
 
    // Use current time as seed for random generator
    srand(time(0));
 
    for(int i = 0; i<4; i++)
        printf(" %d ", rand());
 
    return 0;
}


Output 1:
453 1432 325 89

Output 2:
8976 21234 45 8975

Output n:
563 9873 12321 24132

Ref.

【讨论】:

    【解决方案2】:

    如果在没有先调用srand() 的情况下使用rand() 生成随机数,则您的程序每次运行时都会创建相同的数字序列。

    srand() 函数设置了生成一系列伪随机整数的起点。如果srand()没有被调用,rand()种子被设置为srand(1)

    所以,在程序开始时设置srand(time(0));

    【讨论】:

    • 而且,如果不清楚,每次生成相同的序列是一件好事。它对于调试很重要,更一般地说,对于理解程序在做什么很重要。一旦它工作正常,添加一个种子,以便您获得不同的行为。
    猜你喜欢
    • 1970-01-01
    • 2012-03-14
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 2017-07-03
    • 1970-01-01
    • 2013-12-10
    相关资源
    最近更新 更多