java生成指定范围的随机数
/**
* 如何在程序中生成指定范围的随机数
*
* 生成23-59之间的随机数
*/
public class Test11 {
public static void main(String[] args) {
/**
* Math.random() 生成(0,1)之间的小数,不包括0和1
* 所以生成23-59之间的随机数,首先60-23=37,所以,
* 37*Math.random() 表示生成(0,37)区间的随机数
* 37*Math.random()+23 ,表示生成(23,60)之间的随机数
* (int)(37*Math.random()+23)把生成的随机数强制转换程整型即可
*/
int num = (int)(37*Math.random()+23);
System.out.println(num);
}
}
执行代码如下: