【发布时间】:2014-01-30 09:08:12
【问题描述】:
所以我有一个包含数字 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 与此有关。但是我不知道如何知道随机数的限制,而不是通过将浮点数转换为字符串然后获取具有最多字符的值。请帮忙。
【问题讨论】:
-
C++ 有一个更好的随机库
<random>明确支持非均匀分布。现在您需要编写自己的发行版,因为它特定于您的情况,但这只需要涵盖发行版部分 - 而不是随机数生成部分。 -
在生成每个号码之前调用
srand并没有帮助。如果您坚持使用rand,请在程序开始时调用一次srand。