【问题标题】:JavaScript - random word generatorJavaScript - 随机词生成器
【发布时间】:2020-03-01 07:17:41
【问题描述】:

我很好奇为什么当我生成随机词并签入console.log 时,math.floor 的结果比math.ceil 好。

为什么math.ceil 不能完美运行? math.ceilmath.random 不兼容,还是我如何分配字符串元素的数组编号(项)?

【问题讨论】:

    标签: javascript math


    【解决方案1】:

    Math.random() 返回一个小于 1(不包括)但大于 0(包括)的数字

    Math.floor(Math.random() * 10); // returns a random integer from 0 to 9
    
    Math.ceil(Math.random() * 10); // returns a random integer from 0 to 10 with a very low chance of 0
    

    如果Math.random 的结果恰好是0,则Math.floor()Math.ceil() 都将返回0,但如果Math.random() 的结果是0.00000001Math.floor() 返回0 和@987654@3返回1

    【讨论】:

    • Math.ceil(Math.random()*10) 返回 1 到 10
    • @MBadrian 正如所解释的,由于Math.random() 的工作方式,Math.ceil(Math.random()*10) 可以返回 0,但概率极低 (stackoverflow.com/questions/52089553)
    【解决方案2】:

    如果您使用Math.ceil(Math.random()*10),您将丢失第一个号码,如果您使用Math.floor(Math.random()*10),您将丢失最后一个号码 但是如果你使用Math.round(Math.random()*10)你可以找到0到10个数字

    var k=2.1
    console.log(Math.ceil(k))
    console.log(Math.floor(k))
    console.log(Math.round(k))
     k=2.6
    console.log(Math.ceil(k))
    console.log(Math.floor(k))
    console.log(Math.round(k))

    【讨论】:

    • Math.round() 的问题是它的最后数字的概率不平衡:0-0.49 => 0(概率:1/6)0.5-1.49 => 1(概率:1/3)1.5-2.49 => 2(概率: 1/3) 2.5-3 => 3 (概率: 1/6)
    猜你喜欢
    • 2017-09-03
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多