最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Calculating 2 ^ 10 - Stack Overflow

programmeradmin4浏览0评论
   // CALCULATE 2 ^ 10
   var base = 2;
   var power = 0;
   var answer = 1; 

   while ( power < 10 )
   {
      answer = base * 2;
      power = power +  1;  
   }

   alert(answer);

Why doesn't this produce 1024? It prints 4.

   // CALCULATE 2 ^ 10
   var base = 2;
   var power = 0;
   var answer = 1; 

   while ( power < 10 )
   {
      answer = base * 2;
      power = power +  1;  
   }

   alert(answer);

Why doesn't this produce 1024? It prints 4.

Share Improve this question edited Jun 15, 2011 at 18:02 JAiro 6,0092 gold badges23 silver badges21 bronze badges asked Jun 15, 2011 at 17:59 industanindustan 232 bronze badges 0
Add a ment  | 

9 Answers 9

Reset to default 4

It is because base * 2 will always be 4.

I believe this line:

answer = base * 2;

Should be

answer = answer * base;

This doesn't really answer your question (as to why the wrong value is generated) but you can use Math.pow to calculate the result:

alert(Math.pow(2, 10));

Your logic is flawed:

...
answer = base * 2; 
...

This resolves to answer = 2 * 2, no matter how many times you increment the loop. base does not change.

Because answer = base * 2; every iteration. Since base never changes, every iteration you are doing answer = 2 * 2;.

See other answers for what you should be doing.

This is because no matter how many loop cycles you do, you always multiply base (2) by 2 and assign the result to answer variable. So be it one or million base, the answer will always be 4.

You need to save the result of each oparation, like this:

    var base = 2;
    var power = 1;
    var answer = 1; 

    answer = base;

     while ( power < 10 ) { 
        answer = answer * base;
        power = power + 1;  
     }

     alert(answer);

This helps you?

If this is for homework... A dynamic programming solution which will help when you get into recursion and other fun stuff:

This solution is log(y) in terms of calculations.

  function powers(x,y) {
        if(y == 0) {
                return 1;
        } else if(y == 1) {
                return x;
        } else if(y == 2) {
                return x*x;
        } else if(y%2==0) {
                var a = powers(x,y/2); 
                return a * a;
        } else {
                var pow = y-1;
                var a = powers(x,pow/2);
                return x * a * a;
        }
}

If not use Math.pow()

Why don't you use the math power method for javascript:

http://www.w3schools./jsref/jsref_pow.asp

yo should do this

var base = 2;
var power = 0;
var answer = 1; 
while ( power < 10 )
{
   answer = answer * 2;
   power = power +  1;  
}

alert(answer);

You have to increment answer otherwise It will always have the same value

发布评论

评论列表(0)

  1. 暂无评论