下面是我的代码,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没有发现任何bug。
如果你能解释我的错误在哪里,我将非常感激(-s)
var counter = 0;
var result = Math.pow (2, counter);
while (result < Math.pow (2, 10)) {
console.log(result);
counter = counter + 1;
}发布于 2016-06-06 20:19:27
正如juvian在注释中所述,您正在更新while循环中的变量“计数器”,但也需要在每个循环中更新“结果”。下面是您的代码的修订版,并给出了说明。
// 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;
}发布于 2016-06-06 20:13:43
另一种写法是:
var result = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function (num) {
return Math.pow(2, num)
})发布于 2016-06-06 20:20:47
在结果计算中,从不使用增量计数器。尝尝这个。
var counter = 0;
while (Math.pow (2, counter) < Math.pow (2, 10)) {
console.log(Math.pow (2, counter));
counter = counter + 1;
}https://stackoverflow.com/questions/37665978
复制相似问题