如何生成随机数以得出固定结果?

问题描述 投票:0回答:1

我有这个公式:

((x + y +(z-7))/ 4.8 = 3.2

我希望能够为x和y生成从1到6的随机数(整数),对于z生成从1到8的随机数(整数),以获得3.2的最终结果。

我尝试了嵌套循环,但不知怎么了:(我正在学习Javascript。

感谢您的帮助。

javascript random
1个回答
0
投票

您可以使用此代码段,但我不确定,为什么输出始终不是3.2。我正在执行Math.random,每次调用函数时都在其中创建范围。

然后将这些值添加到您的公式中。

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

const x = getRandomInt(1,6)
const y = getRandomInt(1,6)
const z = getRandomInt(1,8)


console.log('x', x)
console.log('y', y)
console.log('z', z)

const result = (x + y + (z-7))/4.8



console.log(result)
© www.soinside.com 2019 - 2024. All rights reserved.