admin管理员组文章数量:1356056
// 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 09 Answers
Reset to default 4It 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
本文标签: javascriptCalculating 210Stack Overflow
版权声明:本文标题:javascript - Calculating 2 ^ 10 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743941571a2565657.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论