简体   繁体   English

如何在获取用户输入时阻止发生无限循环?

[英]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.

相关问题 Discord Bot 开发:如何停止这种无限循环? - Discord Bot Development: How do I stop this infinite loop? 如何在不使用Break的情况下停止无限提示循环? - How do I stop an infinite prompt loop without using Break? 生成大型二进制网格时如何防止发生无限调用堆栈? - How do I prevent an infinite call stack from occurring when generating a large binary grid? 有时如何阻止无限滚动 ajax 帖子获得双倍的结果 - How do I stop infinite scroll ajax post from getting double the results sometimes 在while循环中的javaScript中如何让程序停止以获取用户输入? - In javaScript during a while loop how do you make the program stop to get user input? 如何停止 Javascript 中的无限循环? - How do you stop an infinite loop in Javascript? onClick function 在渲染时被调用——我怎样才能阻止这种情况的发生? - onClick function is called on render -- how can I stop this from occurring? 在我的函数运行时如何解除绑定或阻止其他单击事件发生? - How do I unbind or prevent other click events from occurring while my function is running? 如何在检测浏览器语言时停止javascript的无限循环 - How to stop infinite loop of javascript while detecting browser language 如何在for循环中阻止条件语句同时运行if子句和else子句? - How do I stop my conditional from running both the if clause and else clause while inside of a for loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM