简体   繁体   中英

Exercise loop “while” - JavaScript

I am stuck on a task. The exercise is based on the "while" loop.

This is what i need to get as output using a variable that changes the numbers and simply printing "Case" and "Notes".

Case 1 : 1 Note
Case 2 : 2 Notes
Case 3 : 4 Notes
Case 4 : 8 Notes 

Here is my code:

function main()
                {
                    var i = 1; 

                    while(i <= 64){
                        document.write("Case " + i + " : " + (i * 1) + " notes" +  "<br>");

                        i = i*2;
                    }


                }

                main();

Here is my result:

Case 1 : 1 notes
Case 2 : 2 notes
Case 4 : 4 notes
Case 8 : 8 notes

As you can see the result is not what i need: i get 1,2,4,8 next to "Case", it should be 1,2,3,4.

Try with this:

function main() {
  var i = 0;
  while (i < 4) { 
    document.write('Case ' + (i + 1) + ' : ' + Math.pow(2, i) + ' Notes'); 
    i += 1; 
  }
}

You can simply add a seperate index counter for the case counting. Something like this:

 function main() { var i = 1; var j = 1; while(i <= 64){ document.write("Case " + j + " : " + i + " notes" + "<br>"); i = i*2; j++; } } main(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM