当前位置:   article > 正文

使用Math.random()产生给定范围内的随机数(java)_math.random生成随机数范围

math.random生成随机数范围

使用Math.random()产生给定范围内的随机数
         *Math.random()本身可以产生[0,1)内的任意随机浮点数,利用Math.random()进行四则运算
         *则可以产生给定范围内的整数或浮点数  

         *详解在代码注释里

  1. package com.atcording.java;
  2. public class RandomTest {
  3. public static void main(String[] args){
  4. /*
  5. * 使用Math.random()产生给定范围内的随机数:
  6. * Math.random()本身可以产生[0,1)内的任意随机浮点数,利用Math.random()进行四则运算
  7. * 则可以产生给定范围内的整数或浮点数
  8. */
  9. double num1,num2;
  10. num1=Math.random()*90;//任意产生[0.090.0)的浮点数
  11. num2=Math.random()*90+10;//任意产生[10.0100.0)的浮点数
  12. int num3=(int)(Math.random()*90+10);//任意产生[1099]的整数
  13. //(int)可以把后面的(Math.random()*90+10)这个浮点型数强制转化为整型
  14. //因为Math.random()*90+10产生的数范围为[10.0100.0),但像99.10这种小数强
  15. //制转化为整型取整后为99,所以整数范围为[1099]
  16. int num4=(int)(Math.random()*90+1+10);//任意产生[10100]的整数
  17. //公式:[a,b]:(int)(Math.random()*(b-a+1)+a)
  18. System.out.println(num1);
  19. System.out.println(num2);
  20. System.out.println(num3);
  21. System.out.println(num4);
  22. }
  23. }

输出结果如下: 

 

 

如果有用就点个赞吧!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/54548
推荐阅读
相关标签
  

闽ICP备14008679号