【发布时间】:2016-05-18 09:54:35
【问题描述】:
我正在尝试获取一个随机值,但这不起作用。
我以此为例。
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)
【问题讨论】:
-
您是否多次致电
srand(time(NULL) ^ getpid());?如果您使用与time()相同的值调用srand(),则会重置“随机”数字生成。 -
rand()是---已弃用---又旧又丑。考虑改用<random>。 -
仅供参考,除非您的流程中只创建了一个
Worms对象曾经(并且根据您的输出判断,情况并非如此),否则srand确实不属于该构造函数;它属于只执行一次的代码块,通常是main()的头部。我完全同意 Bartek。<random>是现代 C++ 程序的晚餐,我强烈鼓励它。 -
See related question 并考虑它如何适用于您的情况。
-
也请阅读Minimal, Complete, Verifiable Examples。只需几行任何人都可以编译的完整代码,就很容易证明这个问题。而且这个问题与食人魔无关。