【问题标题】:Infinitely repeating for loop [duplicate]无限重复for循环[重复]
【发布时间】:2020-06-06 09:37:20
【问题描述】:

我一直在尝试创建一个简单的随机数生成器,以此来应用我在 JavaScript 中学到的一些知识,它似乎在无限重复某个值。

当然,它的主要目的是随机生成一个介于HIGH[est]LOW[est] 值之间的数字,用户可以从 Windows 上的命令提示符输入。

但它所做的是无限重复LOW 变量。到目前为止,我已经尝试在多个地方添加break;,但无济于事。我也没有返回任何具体的错误。

我认为问题在于,我搞砸了作为循环参数 (?) 包含的 3 个语句。不过我不完全确定,所以我需要一些帮助。请原谅我对所有这些术语的文盲,我现在才开始弄清楚所有这些。

代码如下:

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("What number would you like to set to your LOW value? ", function(LOW) {
    rl.question("What number would you like to assign to the HIGH? ", function(HIGH) {
        console.log(`Generating a random number between ${LOW} and ${HIGH}...`);
        for(let rng = LOW; rng < HIGH; Math.floor(Math.random) * HIGH) {
            if (rng < LOW) {
                console.log("Arithmetic err")
                break;
            } else if (rng > HIGH) {
                console.log("Arithmetic err")
                break;
            }
        };
        console.log(`Your result is: ${rng}`); break;
    });
});

rl.on("close", function() { 
    console.log("\nDone!")
    process.exit(0);
});

【问题讨论】:

  • 您认为 rng 变量的更新情况如何?这就是为什么无限循环
  • 你是在节点上做这个吗?
  • for 循环的第三条语句 (Math.floor(Math.random) * HIGH) 没有执行任何操作。它没有被持久化,所以它只是计算然后进入垃圾收集器。
  • 还需要调用Math.random函数:Math.floor(Math.random() * HIGH)

标签: javascript loops for-loop random


【解决方案1】:

您不需要循环,只需在LOWHIGH 之间生成一个数字即可:

Math.floor(Math.random() * (HIGH - LOW)) + LOW

但您可能想检查用户输入的LOW 是否高于HIGH

if (LOW < HIGH) {
  console.log(`Generating a random number between ${LOW} and ${HIGH}...`);
  const rng = Math.floor(Math.random() * (HIGH - LOW)) + LOW;
  console.log(`Your result is: ${rng}`);
} else {
  console.log(`Your LOW number should be lower than your HIGH number.`);
}

演示包括从字符串到数字的转换,以及检查是否输入了除数字以外的其他内容:

// Only for the demo to work here
const rl = { question(q, cb) { cb(prompt(q)); } };

rl.question("What number would you like to set to your LOW value? ", function(low) {
  rl.question("What number would you like to assign to the HIGH? ", function(high) {
    // Convert these Strings to Numbers
    const LOW = Number(low), HIGH = Number(high);
    // Check if they are numbers (isNaN stands for is Not a Number)
    if (isNaN(LOW) || isNaN(HIGH)) {
      console.log(`You should only enter numbers.`);
    } else if (LOW < HIGH) {
      console.log(`Generating a random number between ${LOW} and ${HIGH}...`);
      const rng = Math.floor(Math.random() * (HIGH - LOW)) + LOW;
      console.log(`Your result is: ${rng}`);
    } else {
      console.log(`Your LOW number should be lower than your HIGH number.`);
    }
  });
});

【讨论】:

    猜你喜欢
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 2018-06-20
    • 2013-03-22
    • 2011-03-31
    • 2013-12-24
    相关资源
    最近更新 更多