java 包容性和排他性的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36378316/
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
Difference between inclusive and exclusive?
提问by Austin Brown
I feel like it's a simple concept, but I'm having trouble with inclusive and exclusive: particularly concerning random number generator.
我觉得这是一个简单的概念,但我在包容性和排他性方面遇到了麻烦:特别是关于随机数生成器。
For instance, if I wanted a value 2-8 (including 2 and 8), that would be inclusive, correct?
例如,如果我想要一个值 2-8(包括 2 和 8),那将是包含的,对吗?
And how would that code look? Something like this: nextInt(8 - 2) + 2; ?
那个代码看起来怎么样?像这样: nextInt(8 - 2) + 2; ?
回答by KevinO
Inclusive means it includes the number. Exclusive means it does not. The Random.nextInt(limit)
is inclusive of 0, and exclusive of the limit. This approach allows using, e.g., the size of an array in a random number:
包含意味着它包括数字。独家意味着它没有。该Random.nextInt(limit)
是包容性的0和独家的极限。这种方法允许使用,例如,随机数中数组的大小:
int[] arr = new int[6]; //size will be 6
Random rnd = new Random();
int i = arr[rnd.nextInt(arr.length)); //will return between [0] and [5]
For a value between 2 and 8, you know that the .nextInt(limit)
will return between 0 and limit, so .nextInt(7) + 2
will give a random number between 0 (inclusive) and 7 (exclusive, which is 6). Adding + 2 will be between 2 and 8 (inclusive of both), since it will be between (0 + 2) and (6 + 2).
对于 2 到 8 之间的值,您知道.nextInt(limit)
将返回 0 和限制之间的值,因此.nextInt(7) + 2
将给出 0(含)和 7(不含,即 6)之间的随机数。添加 + 2 将介于 2 和 8 之间(包括两者),因为它将介于 (0 + 2) 和 (6 + 2) 之间。
回答by Elliott Frisch
For instance, if I wanted a value 2-8 (including 2 and 8), that would be inclusive, correct?
例如,如果我想要一个值 2-8(包括 2 和 8),那将是包含的,对吗?
Yes. Inclusive includes; Exclusive excludes.
是的。包容性包括;独家排除。
The range 2-8
inclusive is 7 unique values (2,3,4,5,6,7,8); and Random.nextInt(int)
excludesthe specified value. So you want something like
2-8
包含的范围是 7 个唯一值 (2,3,4,5,6,7,8);和不包括所述指定的值。所以你想要类似的东西Random.nextInt(int)
Random rand = new Random();
int min = 2;
int max = 8;
// ...
int r = rand.nextInt((max - min) + 1) + min;