是否可以使用带 Math.pow 的 while 循环显示 2 的 1,2...10(最大)次方行?
Is it possible to display the row of 2 in the power of 1,2...10 (the biggest) using while loop with Math.pow?
这是我的代码,t work. It seems to me that it has to but when I use console (in inspect section in the browser) nothing happens, it doesn
没有发现任何错误。
如果你能告诉我错误在哪里,我将不胜感激(-s)
var counter = 0;
var result = Math.pow (2, counter);
while (result < Math.pow (2, 10)) {
console.log(result);
counter = counter + 1;
}
另一种写法是:
var result = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function (num) {
return Math.pow(2, num)
})
正如 juvian 在评论中所述,您正在更新 while 循环中的变量 "counter",但您还需要在每个循环中更新 "result"。这是您的代码的修订版,并附有解释。
// Counter starts at zero
var counter = 0;
/*
Result needs to be initialized to check the
initial condition.
Alternatively, we could have changed the
condition of the while loop to something like:
while (counter <= 10) { ... }
(this would be technically faster because
you're not re-computing Math.pow(2,10))
*/
var result = 0;
// We perform the code in here until the condition is false
while (result < Math.pow (2, 10)) {
// First, we raise 2 to the power of counter (0 the first time)
var result = Math.pow (2, counter);
// Print the result
console.log(result);
// Now increment the counter
// (this will change what the first line of the loop does)
counter = counter + 1;
}
递增的计数器从不用于结果计算。试试这个。
var counter = 0;
while (Math.pow (2, counter) < Math.pow (2, 10)) {
console.log(Math.pow (2, counter));
counter = counter + 1;
}
这是我的代码,t work. It seems to me that it has to but when I use console (in inspect section in the browser) nothing happens, it doesn
没有发现任何错误。
如果你能告诉我错误在哪里,我将不胜感激(-s)
var counter = 0;
var result = Math.pow (2, counter);
while (result < Math.pow (2, 10)) {
console.log(result);
counter = counter + 1;
}
另一种写法是:
var result = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function (num) {
return Math.pow(2, num)
})
正如 juvian 在评论中所述,您正在更新 while 循环中的变量 "counter",但您还需要在每个循环中更新 "result"。这是您的代码的修订版,并附有解释。
// Counter starts at zero
var counter = 0;
/*
Result needs to be initialized to check the
initial condition.
Alternatively, we could have changed the
condition of the while loop to something like:
while (counter <= 10) { ... }
(this would be technically faster because
you're not re-computing Math.pow(2,10))
*/
var result = 0;
// We perform the code in here until the condition is false
while (result < Math.pow (2, 10)) {
// First, we raise 2 to the power of counter (0 the first time)
var result = Math.pow (2, counter);
// Print the result
console.log(result);
// Now increment the counter
// (this will change what the first line of the loop does)
counter = counter + 1;
}
递增的计数器从不用于结果计算。试试这个。
var counter = 0;
while (Math.pow (2, counter) < Math.pow (2, 10)) {
console.log(Math.pow (2, counter));
counter = counter + 1;
}