gpt4 book ai didi

javascript - 生成四个随机数,使其相加达到最大值

转载 作者:行者123 更新时间:2023-11-28 00:20:43 25 4
gpt4 key购买 nike

首先我想说这个问题可能有类似的问题,但我的问题非常不同。

我正在生成四个随机数,但是当其中一个数字低于 max/10 或高于 max/1.2 时,我想再次加载该函数,直到得到正确的随机数。我在脚本中这样写:

if (first < max / 10 || second < max / 10 || third < max / 10 || fourth < max / 10) { reken(max); }
if (first > max / 1.2 || second > max / 1.2 || third > max / 1.2 || fourth > max / 1.2) { reken(max); }

但这对我不起作用。我得到的数字低于 10,有时高达 85。当在 if 语句后面添加一些愚蠢的内容(例如: if(){ asdhbjka } )时,代码会崩溃并等待另一秒来运行脚本。这样我就得到了好的数字。所以我知道我的 if 语句有效,只是 reken(max);

有问题

Soo..希望你能帮助我。

function random(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}

function reken(max) {
var status = document.getElementById('status');
var max = 100
var first = random(1, max / 2.0 - 3);
var second = random(1, max / 1.5 - 2 - first);
var third = random(1, max / 1.2 - 1 - first - second);
var fourth = max - first - second - third;
if (first < max / 10 || second < max / 10 || third < max / 10 || fourth < max / 10) {
reken(max);
}
if (first > max / 1.2 || second > max / 1.2 || third > max / 1.2 || fourth > max / 1.2) {
reken(max);
}

status.innerHTML = first + " - " + second + " - " + third + " - " + fourth + " / " + (first + second + third + fourth );
}
var animateInterval = setInterval(reken,1000);
<p id="status"></p>

最佳答案

你的问题可以在你的递归调用中找到。

让我们简单一点:

function findNumber()
{
var number = random(0,10);
if (number < 5)
findNumber();

document.GetElementById("labelForMyNumber").innerText(number);
}

让我们运行该代码..会发生什么:

Step 1: number = 6

Step 2: if fails (number > 5)

Step 3: label get text: 6

好的,我们现在再试一次:

Step 1: number = 4

Step 2: If succeeds (number < 5)

Step 3: we call the function again

Step 4: new number, this time 8

Step 5: If fails (8 > 5)

Step 6: We change the text to 8.

BUT!! Step 7: We return to the first function! Number is now 4 again (see step 1)

Step 8: We change the text to number which is 4.

你看到了吗?当你进行递归时,你总是返回到之前的函数,并继续执行该代码。

现在,如何解决这个问题?

简单的方法是这样的:

function findNumber()
{
var number = random(0,10);
if (number < 5)
findNumber();
else
document.GetElementById("labelForMyNumber").innerText(number);
}
<小时/>

按照这个逻辑,你的代码应该是:

function reken(max) {
var status = document.getElementById('status');
var max = 100
var first = random(1, max / 2.0 - 3);
var second = random(1, max / 1.5 - 2 - first);
var third = random(1, max / 1.2 - 1 - first - second);
var fourth = max - first - second - third;
if ((first < max / 10 || second < max / 10 || third < max / 10 || fourth < max / 10) || (first > max / 1.2 || second > max / 1.2 || third > max / 1.2 || fourth > max / 1.2) {
reken(max);
}
else {
status.innerHTML = first + " - " + second + " - " + third + " - " + fourth + " / " + (first + second + third + fourth );
}
}

关于javascript - 生成四个随机数,使其相加达到最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30053265/

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