gpt4 book ai didi

javascript - 来自特定数字范围的连续三个随机数 - JavaScript

转载 作者:行者123 更新时间:2023-11-29 21:05:54 26 4
gpt4 key购买 nike

我是 JavaScript 的新手,想编写代码,显示 0-6 范围内的三个随机数。问题是,我还希望这三个数字是连续的,例如 - 1,2,3 或 3,4,5 等等。这是我的代码:

var location1 = 0;
var location2 = 0;
var location3 = 0;

function place_ship(){
var location1 = Math.floor(Match.random() *6);
if (location1 == 0){
var location2 = 1;
var location2 = 2;
}
else if(location1 == 6){
var location2 = 5;
var location2 = 4;
}
else{
while (var location2 != (location2 != location1 && (location2 = location1 - 1 || location2 = location1 + 1))){
var location2 = Math.floor(Math.random() *6;
}
while((location3 != location1 && location3 != location2) && (((location3 = location2 - 1 || location3 = location2 + 1)) || ((location3 = location1 + 1 || location3 = location1 - 1)))){
var location3 = Math.floor(Math.random() *6;
}
}
}

document.write(location1 + location2 + location3);

最佳答案

您可以将船的长度和航程作为随机数的因素。结果是船的起始位置。

var shipLength = 3,
range = 6,
random = Math.floor(Math.random() * (range - shipLength + 2));

console.log(random);

关于javascript - 来自特定数字范围的连续三个随机数 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44098788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com