无限重复循环

时间:2020-02-21 23:16:39

标签: javascript loops for-loop random

我一直在尝试创建一个简单的随机数生成器,以应用我从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);
});

1 个答案:

答案 0 :(得分:0)

您不需要循环,只需在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.`);
    }
  });
});