[英]How do I stop an infinite loop from occurring while getting user input?
I'm a newbie writing a program that continues to ask the user for a number until the entered number is less than or equal to 100. I keep ending up in an infinite loop and I'm unsure of how to add the correct conditions to end the loop. 我是一名新手,正在编写程序,继续询问用户输入的数字,直到输入的数字小于或等于100。我一直处于无限循环状态,不确定如何添加正确的条件。结束循环。
let num;
while (!(num === 100 && num < 99)) { // infinite loop
num = Number(prompt("Enter a number: "));
console.log(num);
}
I want to exit the loop when the user enters a number less than or equal to 100. 当用户输入小于或等于100的数字时,我想退出循环。
let num = 101; while (num > 100) { num = Number(prompt("Enter a number: ")); console.log(num); }
Or with Do/While: 或使用“执行/同时执行”:
let num; do { num = Number(prompt("Enter a number: ")); console.log(num); } while (num > 100);
let num; while (true) { num = Number(prompt("Enter a number: ")); if (num <= 100) { break; } }
To resolve this issue use either 若要解决此问题,请使用
!(num === 100 || num < 100) or
!(num <= 100)
Issue: Num can never be both equal to 100 and less than 99 , so it will be false always and so while condition is true always 问题: Num不能永远等于100且不能小于99,因此它始终为假,因此当条件始终为true时
let num; while (!(num <= 100)) { //or !(num === 100 || num < 100) num = Number(prompt("Enter a number: ")); console.log(num); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.