首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否可以用Math.pow循环显示1,2.10(最大的)2行?

问是否可以用Math.pow循环显示1,2.10(最大的)2行?
EN

Stack Overflow用户
提问于 2016-06-06 20:06:39
回答 3查看 42关注 0票数 0

下面是我的代码,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)

代码语言:javascript
复制
var counter = 0;
var result = Math.pow (2, counter);
    while (result < Math.pow (2, 10)) {
    console.log(result);
    counter = counter + 1;
    }
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-06-06 20:19:27

正如juvian在注释中所述,您正在更新while循环中的变量“计数器”,但也需要在每个循环中更新“结果”。下面是您的代码的修订版,并给出了说明。

代码语言:javascript
复制
// 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;
}
票数 0
EN

Stack Overflow用户

发布于 2016-06-06 20:13:43

另一种写法是:

代码语言:javascript
复制
var result = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function (num) {
  return Math.pow(2, num)
})
票数 0
EN

Stack Overflow用户

发布于 2016-06-06 20:20:47

在结果计算中,从不使用增量计数器。尝尝这个。

代码语言:javascript
复制
var counter = 0;
while (Math.pow (2, counter) < Math.pow (2, 10)) {
  console.log(Math.pow (2, counter));
  counter = counter + 1;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37665978

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档