TariqAbu Posted April 1, 2014 Share Posted April 1, 2014 I'm writing a program that calculates and shows the value of 210 (2 to the 10th power). This is my code and it prints out 2048 instead of the 1024 (the right answer). var result = 2; for (var i = 0; i < 10; i++){ result = result * 2; }; print(result); could someone explain to me what am i missing here? Link to comment Share on other sites More sharing options...
Ingolme Posted April 1, 2014 Share Posted April 1, 2014 Since you're starting off with 2, you're adding one more to the exponent. You can start with var i = 1 Link to comment Share on other sites More sharing options...
davej Posted April 1, 2014 Share Posted April 1, 2014 <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>powers of 2</title><style>div{border:1px solid #000;width:100px;background-color:#ccc;}span{margin:3px 5px;font-weight:bold;font-size:14pt;}</style><script>window.onload = init;function init() {document.getElementById('btn1').onclick = pow;}function pow(){var result = 1;var str = "";for (var i=0 ; i<=10 ; i++){str += '<span>2<sup>'+ i +'</sup> = '+ result +'</span><br/>';result = result * 2;}document.getElementById('out1').innerHTML = str;}</script></head><body><input type="button" id="btn1" value="Run"/><div id="out1"></div></body> </html> Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now