0
因此,我有一张地图< int,float>包含数字1 - 6的偏差。我需要返回一个有偏差的值。请注意,由于用户输入的偏差不是恒定的。它在一个类中,所有的变量都已经被声明。随机数与偏差
所以这就是我到目前为止所做的。
int die:: randomNumber(map < int, float > &biasPercent)
{
randomString[0] << biasPercent[0];
randomArray[0] = randomString[0].str();
maximum = randomArray[0].size();
for(counter = 0; counter < 6; counter++)
{
randomString[counter] << biasPercent[counter];
randomArray[counter] = randomString[counter].str();
if(randomArray[counter].size() > maximum)
{
maximum = randomArray[counter].size();
}
}
limit = 1;
for(counter = 1; counter <= maximum - 2; counter++)
{
limit *= 10;
}
srand(time(NULL));
random1 = rand() % limit + 1;
if(random1 <= biasPercent[0] * limit)
{
return 1;
}
else if(random1 > biasPercent[0] * limit && random1 <= (biasPercent[0] * limit) + (biasPercent[1] * limit))
{
return 2;
}
else if(random1 > ((biasPercent[0] * limit) + (biasPercent[1] * limit) * limit) && random1 <= (((biasPercent[0] * limit) + (biasPercent[1] * limit)) + (biasPercent[2] * limit)))
{
return 3;
}
else if(random1 > (((biasPercent[0] * limit) + (biasPercent[1] * limit)) + (biasPercent[2] * limit)) && random1 <= (((((biasPercent[0] * limit) + (biasPercent[1] * limit)) + (biasPercent[2] * limit))) + (biasPercent[3] * limit)))
{
return 4;
}
else if(random1 > (((((biasPercent[0] * limit) + (biasPercent[1] * limit)) + (biasPercent[2] * limit))) + (biasPercent[3] * limit)) && random1 <= ((((((biasPercent[0] * limit) + (biasPercent[1] * limit)) + (biasPercent[2] * limit))) + (biasPercent[3] * limit))) + ((biasPercent[4] * limit)))
{
return 5;
}
else
{
return 6;
}
}
它似乎不工作,因为它只能始终返回1。我猜测stringstream与此有关。但我不知道如何知道随机数的限制,而不是将float转换为字符串,然后获取最多字符的值。请帮忙。
C++有一个更好的随机库'',它明确支持非均匀分布。现在你需要编写你自己的发行版,因为它对你的情况很特殊,但只需要覆盖发行版的一部分 - 而不是随机数生成部分。 –
MSalters
在生成每个数字之前调用'srand'并没有帮助。如果你坚持'rand',那么在程序开始时调用'srand'一次。 –