语法:Math.random()
返回值:一个浮点型伪随机数字,在0
(包括 0)和1
(不包括)之间。它不能被用户选择或重置。不可重复使用,想要重复使用随机数的值,只能声明一个变量来保存。
public class Test {
public static void main(String[] args) {
//随机数Math.random();
System.out.println(Math.random()); //随机生成一个0-1中间的浮点数
}
}
如何获取在某一个范围之内的随机数
double number=Math.random()*(max-min)+min;
public class Test {
public static void main(String[] args) {
/*控制随机数的获取范围
* 获取一个999-10000之间的随机数
*/
System.out.println((Math.random()*(10000-999)+999));
}
}
如何获取在某一个范围之内的随机整数
int number=(int)(Math.random()*(max-min)+min);
注:Math.random() 获取的值为一个随机浮点数,如果想要获取一个随机整数就需要强转,注意
——强转会丢失精度
public class Test {
public static void main(String[] args) {
/*控制随机数的获取范围
* 获取一个999-10000之间的随机整数
*/
System.out.println((int)(Math.random()*(10000-999)+999));
}
}