我知道这类问题已经被问到几次,但是其中很多答案归结为RTFM,但我希望我能问正确的问题...我可以为其他所有人提供准确的答案好吧,关于实施。

我正在尝试以以下两个方式生成一系列随机数:

#include <cstdlib>
#include <ctime>
#include <cmath>

#include "Cluster.h"
#include "LatLng.h"

 srand((unsigned)time(0));
 double heightRand;
 double widthRand;
 for (int p = 0; p < this->totalNumCluster; p++) {

  Option 1.
  heightRand = myRand();
  widthRand = myRand();

  Option 2.
  heightRand = ((rand()%100)/100.0);
  widthRand = ((rand()%100)/100.0);

  LatLng startingPoint( 0, heightRand,  widthRand );
  Cluster tempCluster(&startingPoint);
  clusterStore.insert( clusterStore.begin() + p, tempCluster);
 }

Myrand()在哪里:

#include <boost/random.hpp>

double myRand()
{
 boost::mt19937 rng;
 boost::uniform_int<> six(1,100);

 boost::variate_generator<boost::mt19937&, boost::uniform_int<> > die(rng, six);

 int tempDie = die();
 double temp = tempDie/100.0;

 return temp;
}

每次运行选项1时,我在每个循环的每个执行中都会获得相同的数字。但是程序的每次运行都不同。

当我运行选项2时,我从Boost库中获得82,因此返回了0.8199999999999。我能理解是否是42岁,但是即使阅读了Boost Random文档,82即使我的头也让我挠头。

有任何想法吗?

DJ。

有帮助吗?

解决方案

使用选项2,您不应创建一个新实例 rngdie 每个电话。

我也不确定我是否正确理解选项1的问题:您仅调用Srand()一次,但是每个调用Rand()给您相同的号码吗?那就是“不寻常”。尝试将循环减少到最小值,并打印从rand()返回的值。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top