首页 > 解决方案 > 如何使用 Math.random() 仅生成十分位的数字?

问题描述

class AlienShip {
    constructor() {
        //random number between 3 and 6
        this.hull = Math.floor(Math.random() * 4) + 3;
        //random number between 2 and 4
        this.firePower = Math.floor(Math.random() * 3) + 2;
        //random number between .6 and .8
        this.accuracy = Math.floor(Math.random() * 1.2) + .6;
    }
}

我试图得到一个介于 0.6 和 0.8 之间的随机数,四舍五入到十分之一。

标签: javascript

解决方案


你可以考虑一个因素和一个调整,最后除以十。

console.log(Math.floor(Math.random() * 3 + 6) / 10)


推荐阅读