虽然循环不工作javascript

时间:2014-11-07 13:11:53

标签: javascript while-loop

我需要帮助这个循环

 <script type="text/javascript">
     var num = window.prompt("enter score");
     var s, a;
     var count=0;
     while (num > 0) {
         s += num;
         count++;
     }
     a = s / count;
     document.write(a); </script>

为什么即使我把数字高于0,这个循环也不起作用?

2 个答案:

答案 0 :(得分:1)

如果您对代码进行评论并逐步完成每个部分,就可以轻松找到问题。

 <script type="text/javascript">
     //Declare a variable of the users choice
     var num = window.prompt("enter score");
     //Declare counters
     var s, a;
     //Declare variable for holding number of times the loop has run
     var count=0;
     //Loop forever if num is greater than 0, since it is never changed
     while (num > 0) {
         //Add n to s. (Where does n come from? - not defined) S is never initialized
         s += n;
         //Add one to count
         count++
     }
     //Set a to be s / count
     a = s / count;
     //Write a to the document body
     document.write(a);
</script>

Document.write将覆盖文档正文中当前的内容 - 有效删除代码。如果您不知道自己在做什么,请不要使用document.write()。

您还应该尝试重写代码,因为可以通过进一步优化来删除大多数行。

修改

Op编辑了代码。

<script type="text/javascript">
     //Define and initialize a value input by the user
     var num = window.prompt("enter score")
     //Define sum (Not initialized) should be "var sum = 0;"
     var sum;
     //Define and initialize count
     var count=0;
     //For as long as num is larger than 0 (loop forever if num is bigger than 0)
     while (num > 0){
          //Add num to sum
          sum += num;
          //Add one to count
          count++;
     }
</script>

我建议你进一步学习javascript,然后逐行完成你的代码。

答案 1 :(得分:0)

while循环中的n个术语看起来不是先前定义的,因此可能是一个问题,而num(num&gt; 0)在num变得小于0时停止循环,但num的值没有得到改变所以它永远不会停止循环。

如果您希望循环计数得分,则可以编写

while(count < num){
   s += n;
   count++;
}

希望这有帮助,

欢呼声