【发布时间】:2021-05-04 15:45:50
【问题描述】:
下面的代码一直在工作,直到在循环中添加条件。
<html>
<body>
<!-- This code is working-->
<script>
var n=parseInt(prompt("Enter a number:"));
while(n>=1){
document.write(n+' / 2<br>');
n=n/2;
}
</script>
</body>
</html>
但是当我添加条件时,同样的代码没有运行:
<html>
<body>
<!-- This code is not working -->
<script>
var n=parseInt(prompt("Enter a number:"));
while(n>=1){
if(n%2!=0){
n=3*n+1;
}
document.write(n+' / 2<br>');
n=n/2;
}
</script>
</body>
</html>
【问题讨论】:
-
你用调试器单步执行了吗?
-
调试器在我尝试运行时挂起/崩溃。(同样的事情发生在多个设备上)
-
您的代码运行。它永远不会停止。
-
对了,你能告诉我为什么会这样吗?
-
问题在于
3*n+1,通过删除它可以正常工作。需要检查错误在哪里
标签: javascript while-loop conditional-statements