Topic: Random 随即数的范围

  Print this page

1.Random 随即数的范围 Copy to clipboard
Posted by: fgh520
Posted on: 2006-04-30 15:51

Math.abs(Random.nextInt()) % 100 + 1
急用,谢谢了。

2.Re:Random 随即数的范围 [Re: fgh520] Copy to clipboard
Posted by: fgh520
Posted on: 2006-04-30 15:52

上面表达式产生随即数的范围是?

3.Re:Random 随即数的范围 [Re: fgh520] Copy to clipboard
Posted by: why
Posted on: 2006-04-30 19:13

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Random.html#nextInt()
nextInt() : All 23^2 possible int values are produced with (approximately) equal probability
However, since the % operator is used,
abs(? % 100) ==> 0 to 99
+ 1 ==> 1 to 100

4.Re:Random 随即数的范围 [Re: fgh520] Copy to clipboard
Posted by: ranchgirl
Posted on: 2006-05-01 00:43

It can be as simple as


int getRandom(int min, int max) {
return min + (int)(Math.random() * (max - min + 1));
}


If you want the random in the range of min to max inclusive.

5.Re:Random 随即数的范围 [Re: fgh520] Copy to clipboard
Posted by: fgh520
Posted on: 2006-05-08 19:32

明白了。在这学到的东西不少啊。
高手很多啊。我还得继续努力啊。


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923