【问题标题】:Rand() Returning Same Value With Every Function Call [duplicate]Rand()在每个函数调用中返回相同的值[重复]
【发布时间】:2014-02-25 00:17:55
【问题描述】:

每当我调用我的类文件中的特定方法时,我都会返回一个随机值,但每次再次调用该方法时它都会继续返回相同的值。

例如

int CommuterTrain::getRandNumber(int maximumValue)
{
    srand(unsigned(time(NULL)));

    int maximum = maximumValue;
    return rand()%maximum+1;
}

void CommuterTrain::loadRiders()
{
    int passengers = getRandNumber(350);
    currentRiders += passengers;
    if (currentRiders > maxCapacity) {
        cout << "The train has reached capacity! \nSome people were left at the station."
                 << endl;
        currentRiders = maxCapacity;
    }
    else {  
        cout<<passengers<<" pax have entered the vessel"<<endl;
    }
}

假设生成器产生了 215 人。当我再次调用该方法时,它不会再次随机化,并且每次都以 215 结束。

是生成器的问题,还是下面的方法?

【问题讨论】:

  • 只播种一次生成器
  • 你为什么每次都播rand?您应该在程序启动时执行一次。
  • Soooooooooooooooo 很多重复...
  • 住手!你不是 Johnny Appleseed 或色情明星!
  • 我认为这赢得了被问到最多的问题。

标签: c++


【解决方案1】:

你一直在重新播种。使用相同的种子(假设您的计算机比 1920 年更新,因此可以在一秒钟内执行您的代码)。不要那样做。

这意味着你一遍又一遍地重新生成并重新启动相同的伪随机序列。因此,每次调用 rand() 时,您都会在该序列中提取相同的第一个值。

在您的程序中只播种一次

例如,您可以将srand 调用放入main

如果您在新的一秒开始时开始执行,则可能需要大约一秒。整数逻辑等等。随便。

【讨论】:

    【解决方案2】:

    您的问题是,您每次调用函数时都在为随机引擎播种:

    int CommuterTrain::getRandNumber(int maximumValue)
    {
        srand(unsigned(time(NULL))); // <<< This line causes your problems
    
        int maximum = maximumValue;
        return rand()%maximum+1;
    }
    

    当前time() 结果在两次调用getRandNumber() 函数之间不太可能发生显着变化。

    您应该在您的函数外部调用 srand(time(NULL)) 一次(例如,在您的 CommuterTrain 类构造函数中,或者更好地仅从 main() 中调用)。

    【讨论】:

      猜你喜欢
      • 2021-03-20
      • 1970-01-01
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多