javascript - 如何使用 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 之间的随机数,四舍五入到十分之一。
解决方案
你可以考虑一个因素和一个调整,最后除以十。
console.log(Math.floor(Math.random() * 3 + 6) / 10)
推荐阅读
- django - 自定义管理视图中的面包屑 (Django)
- azure - 具有对象 ID 的客户端无权在范围内执行操作“Microsoft.Web/serverfarms/read”
- java - Java Jackson XMLMapper 序列化地图
没有将 XML < 和 > 字符转义为 &lgt; 的对象 >? - ios - 实体“GAIHit”上的 GoogleAnalytics.Property“参数”正在使用 nil 或不安全的 NSValueTransformer
- python - 使用 Python 从 API 访问数据(疑问)
- php - 在 laravel 5.8 中上传图片
- javascript - 测试 package.json types 属性是否适用于相应的 javascript 文件
- git - 更新一个 git 提交
- java - Java Streams - 使用 GroupingBy 和计数收集到地图,但如果特定字段为 Null,则计数为 0
- java - 如何解决我的测试项目中的 io.netty 错误