简体   繁体   English

JavaScript中的无限while循环

[英]infinite while loop in javascript

My problem question as in the practice course goes as follows: 我在练习过程中遇到的问题如下:

Write a JavaScript program to create a function which takes 2 integers as inputs. 编写一个JavaScript程序来创建一个将2个整数作为输入的函数。 The function divides the first integer with second integer as long as the result (Quotient) is an integer (ie remainder is zero) and return the quotient as result. 只要结果(商)是一个整数(即余数为零),该函数就将第一个整数除以第二个整数,并返回商作为结果。 Your output code should be in the format console.log("Result is ", variableName) 您的输出代码应采用console.log(“ Result is”,variableName)格式

And below is my code: 下面是我的代码:

var num = prompt("Enter number to divide");
var d = prompt("Enter divisor");

function divide(x, y) {
  var result;
  if (d === 1) {
    result = num;
  } else {
    while (num % d === 0) { //while error
      result = num / d;
    }
  }
  return result;
}
var output = divide(num, d);
console.log("Result is: ", output);

If I remove the while loop, program works fine but the problem description says I have to use it. 如果删除while循环,程序可以正常运行,但问题描述表明我必须使用它。

What am I doing wrong? 我究竟做错了什么?

Your while loop is depending of num , but you don´t assign a new value to it after a cycle. while循环取决于num ,但是在循环后您不会为其分配新值。 This lead to that the condition stays always the same. 这导致条件始终保持不变。

 var num = prompt("Enter number to divide"); var d = prompt("Enter divisor"); function divide(x, y) { var result = x; if (y === 1) { return result; } else { while (result % y === 0) { result = result / y; } } return result; } var output = divide(num, d); console.log("Result is: ", output); 

There are a few issues: 有几个问题:

1) If your function receives the arguments x and y , then use those inside his scope, don't access the global variables. 1)如果您的函数接收到参数xy ,则在其作用域内使用这些参数,请勿访问全局变量。

2) You are never changing the variables that are evaluated on the while condition, so the evaluation will be the same, ever! 2)您永远不会更改在while条件下求值的变量,因此求值将永远相同!

3) Another good thing you can do is add some validation on the received arguments. 3)您可以做的另一件事是在收到的参数上添加一些验证。

Now, your code, can be rearranged to this one: 现在,您的代码可以重新安排为这一代码:

 function divide(x, y) { if (isNaN(x) || isNaN(y)) return "Invalid arguments!"; if (y === 1) return x; while (x % y === 0) { x = x / y; } return x; } var num = prompt("Enter number to divide"); var d = prompt("Enter divisor"); var output = divide(num, d); console.log("Result is: ", output); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM