即使在srand之后,rand()也会返回相同的值

时间:2016-05-18 09:54:35

标签: c++ random ogre

我想获得一个随机值,但这不起作用。

我以此为例。

  srand(time(NULL) ^ getpid());

  int a = rand() % 100;

我第一次得到一个随机值,但每隔一次我调用rand(),我得到相同的值。

我的完整代码:

Worms::Worms(std::string const& name, Ogre::SceneManager *scene,
  Ogre::ColourValue &color, unsigned char hp) :
  _name(name), _hp(hp), _scene(scene), _color(color)
{
  srand(time(NULL) ^ getpid());
  std::cout << "creating worms" << name << std::endl;
  std::cout << color << std::endl;
  this->_ent = scene->createEntity(name, "Worm.mesh");
  this->generatePosition();
  this->setColor(color);
}

void                            Worms::generatePosition()
{
  int a = rand() % 10;
  std::cout << a << std::endl;
  Ogre::Vector3 pos(rand() % 800 + 100 , 450, 0);
  std::cout << pos << std::endl;
  this->_node = this->_scene->getRootSceneNode()->createChildSceneNode(this->_name);
  this->_node->attachObject(this->_ent);
  this->_node->showBoundingBox(true);
  this->_node->scale(_node->getScale() * 4);
  _node->rotate(Ogre::Vector3::UNIT_X, Ogre::Degree(90));
  _node->rotate(Ogre::Vector3::UNIT_Z, Ogre::Degree(90));
  _node->setPosition(pos);
}

输出:

4
Vector3(498, 450, 0)
creating worms K04L4_1
creating wormsK04L4_1 Captain_2
ColourValue(1, 0, 0, 0)
4
Vector3(498, 450, 0)
creating worms K04L4_1
creating wormsK04L4_1 Captain_3
ColourValue(1, 0, 0, 0)
4
Vector3(498, 450, 0)
creating worms K04L4_1
ok
creating wormsOP3X_2 Pride_1
ColourValue(0, 1, 0, 0)
4
Vector3(498, 450, 0)
creating worms OP3X_2
creating wormsOP3X_2 Captain_2
ColourValue(0, 1, 0, 0)

2 个答案:

答案 0 :(得分:1)

我在程序中多次使用srand(),现在我在main()函数中调用了一次,并且工作正常。

答案 1 :(得分:0)

time(NULL)只有第二个分辨率,所以如果在同一秒内调用你的函数,它将始终使用相同的种子。尝试GetTickCount()达到毫秒分辨率或将微秒ticks传递到srand()

using namespace std::chrono;
auto ticks = time_point_cast<microseconds>(system_clock::now()).time_since_epoch().count();

从64位到32位(srand()需要32位参数)的向下转换特定于编译器,但它通常会丢弃高阶位,这是您想要获得更随机的种子。

正如您所说,您可以拨打srand()一次,然后继续致电rand()。然后,您将逐步完成整个伪随机序列。

相关问题