Calculating 2 ^ 10
// 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? 开发者_StackOverflowIt prints 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.com/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
精彩评论