C语言 生成范围 [min,max] 内的随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29381843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate random number in range [min,max]
提问by John
I am using C to generate a integer random number in range [min max]. I am using
我正在使用 C 生成范围 [min max] 内的整数随机数。我在用
int random_int(int min, int max)
{
return min + rand() % (max - min);
}
But I think above code is for range : [min, max), it is not for [min max]. Could you show to me a code to do my work. Best thanks
但我认为上面的代码适用于范围:[min, max),而不适用于 [min max]。你能不能给我看一个代码来完成我的工作。最好的感谢
回答by SleuthEye
As you guessed, the code does indeed generate random numbers which do not include the maxvalue. If you need to have the maxvalue included in the range of random numbers generated, then the range becomes [min,max+1). So you could simply modify your code to:
正如您所猜测的那样,该代码确实会生成不包含该max值的随机数。如果您需要将max值包含在生成的随机数范围内,则范围变为 [min,max+1)。因此,您可以简单地将代码修改为:
int random_int(int min, int max)
{
return min + rand() % (max+1 - min);
}
P.S.:that is provided the quality of the original 'modulo' pseudo-random number generator you posted was not a concern (see this postfor some more details with respect to what @undefinedbehaviour was referring to in comments).
PS:前提是您发布的原始“模”伪随机数生成器的质量不是问题(有关@undefinedbehaviour 在评论中所指内容的更多详细信息,请参阅此帖子)。

