【发布时间】:2017-06-02 17:44:28
【问题描述】:
我正在为特定种子生成一个随机数...所以我有一个名为seed 的属性,我允许用户设置它。我给了他两个选择:reset 和trigger。 reset 将重新开始生成随机数。而trigger 将生成下一个随机数。伪代码有点像
::setSeed( unsigned & seed )
{
m_seed = seed
}
::reset()
{
m_seed = getcurrentseed()
srand(m_seed);
}
::trigger()
{
raValue = minValue + ( rand() % (maxValue-minValue+1) );
}
对于特定的种子,如果我生成 5 个随机值 5 次 ..有时我会看到其中一个集合中缺少一个值。可能是什么原因 ?
例如。
seed(5)
rand()
rand()
rand()
seed(5)
rand()
rand()
rand()
在第二次 seed(5) 调用之后,有时我会得到不同的数字序列,或者我错过了前一个序列中的数字
void RandomNodeLogic::process( SingleInputValueGetters const& singleInputValueGetters
, MultiInputValueGetters const& /*multiInputValueGetters*/
, OutputValueKeepers const& /*outputValueKeepers */
, OutputValueSetters const& outputValueSetters )
{
// get the seed and generate the random number
bool doRandom( false );
int maxValue= getMaxValue().getAs<int>();
int minValue = getMinValue().getAs<int>();
int newValue=0;
if(minValue > maxValue)
{
setMaxValue(minValue);
setMinValue(maxValue);
maxValue= getMaxValue().getAs<int>();
minValue = getMinValue().getAs<int>();
}
SingleInputValueGetters::const_iterator it = singleInputValueGetters.begin();
for( ; it != singleInputValueGetters.end(); ++it)
{
SlotID id = it->first;
const SlotValue* value = it->second();
if(!value)
{
continue;
}
if ( id == RTT::LogicNetwork::RandomNode::nextValuesSlotID )
{
doRandom = value->getAs<bool>();
newValue = minValue + ( rand() % (maxValue-minValue+1) ); // read the value from the next input slot
setRandomValue( ::convertToSlotValue( m_genValue.m_attrType, newValue ) );
}
else if ( id == RTT::LogicNetwork::RandomNode::resetValuesSlotID )
{
if ( value->getAs<bool>() )
{
doRandom = value->getAs<bool>();
setSeed(m_seed);
newValue = minValue + ( rand() % (maxValue-minValue+1) );
setRandomValue( ::convertToSlotValue( m_genValue.m_attrType, newValue ) );
}
}
}
if(!m_genValue.empty() && doRandom)
{
outputValueSetters.find( RTT::LogicNetwork::RandomNode::outputValuesSlotID)->second( m_genValue.getAs<int>() ) ;
RTT_LOG_INFO( QString("Random Number: %1").arg( m_genValue.getAs<int>() ));
}
if(!doRandom)
{
if(m_genValue.empty())
{
srand(1);
m_genValue = 0;
}
getAssociatedNode()->sleep();
}
}
void RandomNodeLogic::setSeed( const SlotValue& seed )
{
SlotValue oldValue = m_seed;
m_seed = seed;
srand(m_seed.getAs<unsigned int>());
modifiablePropertyValueChanged( RTT::LogicNetwork::RandomNode::seedPropertyID, m_seed, oldValue );
}
【问题讨论】:
-
您使用的是 C 还是 C++?它们不是同一种语言,您可能根本不应该在 C++ 中使用
srand()。 -
为了让我们知道原因,您需要删除伪代码并向我们展示确切代码。
-
给我们复制问题的真实代码。您复制问题的代码调用了一些名为
seed的函数和一些名为rand的函数,它们的代码均未显示。您显示了一些未被调用的名为trigger的代码。等等。我们需要复制问题来理解它。 -
顺便说一句,在
rand() % minValue + ( rand() % (maxValue-minValue+1) )中,rand()的2次调用每次都可以按任意顺序进行。 -
m_seed = getcurrentseed()这是做什么的?我以为m_seed是当前的种子?