您的位置:首页 > 编程语言 > Java开发

《Java编程技巧1001条》358条:控制随机整数的范围

2017-12-19 16:21 246 查看
《Java编程技巧1001条》358条:控制随机整数的范围

358Controlling the Range of Random Integers 358 控制随机数的范围 As you have learned, Java praograms cangenerate random integers by using an instance of the Random class. The Randomclass contains a method called nextInt, which produces a new random int foreach call.
Depending on your programs purpose, you may need to produce randomnumbers - 13 - in a specific range. To control the rnge of integer values arandom-number generator creates, you can use the modulus operator (%). Forexample, if you need numbers in the range
-100 to 100, you can get the remainderof the random number divided by 100, as shown: 正如你已了解的, Java 程序是利用 random 类的一个实例来生成随机数. random 类包含一 个称作 NexrInt 的方法,它为每一次调用产生一个新的随机整型数. 按照你的程序的用途,你可 能需要产生某一范围内的随机数. 为了控制一随机数建立的整数的范围,你可以使用取模运算 符(%). 例如, 若需要 -100 到 100 范围中的数,
可用 100 来除随机数, 求出其余数, 如下: Random r = new Random(); // use a defaultinitial seed System.out.println(Random int is + r.nextInt() % 100); Likewise,if you need to restrict the range of numbers to positive values, say 0 to 100,your programs can use the Math class
abs function, as shown: 同样,如果你要把数值限制在正数范围之内,例如 0 到 100,则你可以在程序中使用 Math 类的 sub 函数,如下所示: Random r = new Random(); // use a defaultinitial seed System.out.println(Random int is + Math.abs(r.nextInt() % 100));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: