一个随机数问题引发的思考
比如要产生65-90的随机数(65<=x<=90),怎么做?(只能用Math.random() 方法)
答案:int num = (int) (Math.random() * 26 + 65);
?
为什么是(Math.random() 乘以26再加上65再取整?
因为Math.random() 产生的随即数范围在0.0<=x<1;
所以Math.random() * 26 会产生0.0<=x<26的随即数,
而Math.random() * 26 + 65会产生(0.0+65)<=x<(26+65)
即:65.0<=x<91.0? => 65.0<=x<=90 .0 再对齐取整数
就是65<=x<=90啦
?
扩展:要产生x-y的随机数呢?(x<=?<=y)
答案:(int)(Math.random()*(y-x+1)+x)