zoukankan      html  css  js  c++  java
  • 随机函数,取整相关问题

    取一定范围的随机整数

    function GetRandomRoundNum(Min,Max) {
    var Range=Max-Min
    return( Math.round(Math.random()*Range+Min))
    }
    var num=GetRandomRoundNum(1,10)
    alert(num)

     

    var arr = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    function GetRandomPart(n) {
    var result= "";
    for(var i = 0; i < n ; i ++) {
    var id = Math.ceil(Math.random()*35);
    result += arr[id];
    }
    return result;
    }
    var num=GetRandomPart(9)
    alert(num)

    相关知识点

    Math类中提供了三个与取整有关的方法

    1.Math.random(): 结果为0-1间的一个随机数(包括0,不包括1) 
    2.Math.floor(num);:参数num为一个数值,函数结果为num的整数部分。 
    3.Math.round(num);:参数num为一个数值,函数结果为num四舍五入后的整数。算法为Math.floor(x+0.5)

    parseInt

    作用:解析一个字符串,并返回一个整数,这里可以简单理解成返回舍去参数的小数部分后的整数。

    如:

    parseInt(5.57)  //返回5

    parseInt(2.4)  //返回2

    parseInt(-1.5)  //返回-1

    parseInt(-5.8)  //返回-5

    拓展

    Math:数学对象,提供对数据的数学计算。
    Math.random(); 返回0和1间(包括0,不包括1)的一个随机数。

    Math.ceil(n); 返回大于等于n的最小整数。
    用Math.ceil(Math.random()*10);时,主要获取1到10的随机整数,取0的几率极小。

    Math.round(n); 返回n四舍五入后整数的值。
    用Math.round(Math.random());可均衡获取0到1的随机整数。
    用Math.round(Math.random()*10);时,可基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。

    Math.floor(n); 返回小于等于n的最大整数。
    用Math.floor(Math.random()*10);时,可均衡获取0到9的随机整数。

    其他一些范围类似

    0~x

    ( Math.round( Math.random()*x) 

    1~x

     Math.ceil( Math.random()*x)       //向上取整

    x ~ y

    Math.round( Math.random()*(y-x) + x )

    ————————————————————————————————————————————————————————————————————————————————————————————————————

    敢想,敢做
  • 相关阅读:
    【基础算法】- 全排列
    【基础算法】- 2分查找
    区块链培训
    Static Binding (Early Binding) vs Dynamic Binding (Late Binding)
    test
    No data is deployed on the contract address!
    "throw" is deprecated in favour of "revert()", "require()" and "assert()".
    Variable is declared as a storage pointer. Use an explicit "storage" keyword to silence this warning.
    京都行
    Failed to write genesis block: database already contains an incompatible
  • 原文地址:https://www.cnblogs.com/ZL8655/p/5379170.html
Copyright © 2011-2022 走看看