zoukankan      html  css  js  c++  java
  • 随机数生成及数舍入的用法

    生成随机数用Math.random()来实现,该方法令系统随机选取大于等于 0.0 且小于 1.0 的伪随机 double 值。

    实例:生成一个随机数

    package my;
    
    public class Test {
        public static void main(String[] args){
            double num= Math.random();
            System.out.println(num);
        }
    }

    运行结果

    0.4661422768062691

    假如要生成一个13-26之间的随机数:(生成一个m-n之间的随机数)

    Math.random()*(26-13)+13;//Math.random()*(n-m)+m

    运行结果:

    15.381155944980378

    常用Math方法

    上舍入方法(取天花板法):Math.ceil(double a)

    package my;
    
    public class Test {
        public static void main(String[] args){
            double num=Math.ceil(0.4);
            System.out.println(num);
        }    
    }

    运行结果

    1.0

    下舍入方法(取地板法):Math.floor(double a)

    package my;
    
    public class Test {
        public static void main(String[] args){
            double num=Math.floor(0.6);
            System.out.println(num);
        }    
    }

    运行结果

    0.0

    四舍五入法:Math.round(double a)

    package my;
    
    public class Test {
        public static void main(String[] args){
            double num1=Math.round(0.4);
            double num2=Math.round(0.6);
            System.out.println(num1);
            System.out.println(num2);
        }    
    }

    运行结果

    0.0

    1.0

  • 相关阅读:
    【node.js】GET/POST请求、Web 模块
    【node.js】全局变量、常用工具、文件系统
    【node.js】函数、路由
    【node.js】模块系统、函数
    【node.js】Stream(流)
    跨域问题的产生,怎么解决它?
    array.splice()
    数组的方法
    js跨域请求的5中解决方式
    3分钟看懂flex布局
  • 原文地址:https://www.cnblogs.com/jonsnow/p/6409741.html
Copyright © 2011-2022 走看看