为什么返回关键字不给我带来理想的结果?
我很想克服这个挑战。我被困了将近2周。这是代码:
function multiply(top,bottom){
var num = top;
var multiple = 2;
while (num <= bottom){
num *= multiple;
console.log(num);
}
return num;
}
console.log(multiply(5, 100));// expected outcome is 80
我很想从Console.log返回80的最后一个结果,但是每次使用返回关键字时,它都不会带来所需的结果。
There is this challenge that I'd love to overcome. I've been stuck for almost 2 weeks. Here is the code:
function multiply(top,bottom){
var num = top;
var multiple = 2;
while (num <= bottom){
num *= multiple;
console.log(num);
}
return num;
}
console.log(multiply(5, 100));// expected outcome is 80
I'd love to return the last result from the console.log which is 80 but each time I use the return keyword, it doesn't bring the desired result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有另一个可跟踪下一个倍数的变量,因此我们可以在将其分配给
num
之前对其进行检查。You have another variable which keeps track of the next multiple, so that we can check it before we assign it to
num
.这里发生的事情是,您正在乘以一个数字并这样做,直到达到欲望结果为止。但是,由于每个步骤都没有添加1个,因此可能会超过结果。
您需要的是具有单独的变量来存储上一个值:
或少1步是在
内进行
条件的计算:What's happening here is that you are multiplying a number and doing so until it reaches the desire result. But since it's not adding 1 with each step it can exceed the result.
What you need is have separate variable to store the previous value:
Or having 1 less step is to do the calculation inside the
while
condition: