我在 Mac 上有这个 dieRole 函数,但是当我将它移动到 Visual C++ 2012 时,结果每次都是 6
int dieRoll() // return a number between 1 and 6
{
static int maxRange = RAND_MAX / 6 * 6;
int result;
do
{
result = rand();
}
while(result > maxRange);
return result % 6 + 1;
}
最佳答案
考虑调用 srand()
。您可以使用时间或进程 ID 提供不同的种子。请记住,这是伪随机性,不一定是您认为的“随机”。
int main()
{
srand(time(NULL));
std::cout << dieRoll() << std::endl;
}
尝试上面的代码大约每秒都会产生不同的结果。 :-)
关于c++ - Visual C++ 中的随机函数不是随机的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18885917/