关于Math.random();的说明

关于Math.random();的关系:
一、随机产生某区间的数:int (Math.random() * (最大值 - 最小值) + 最小值)
一、Math.random(); 在Java中式产生随机产生 [0,1) 之间的数
创建一个方法:返回一个m~n 的值,包括m 但不包括 n ,如果返回 -1 表示输入错误。
// 返回一个m~n的随机整数,包括m,不包括n。如果返回-1,表示函数的参数有问题 public static void main(String[] args) { //为了验证结果,输出十次 for (int i = 0; i <= 10; i++) { System.out.println(sum(10, 20)); } } public static int sum(int m, int n) { // 判断是不是输入争取 if (n < m) { return -1; } double a = Math.random() * (n - m) + m; return (int) a; }
Java控制台输出:
12 14 16 18 12 19 14 18 12 14 17
作者:域名博客,网站地址:https://liuguangfa.com/,转载注明出处!