如何使用JavaScript中的while循环计算平均值

时间:2014-11-17 01:37:15

标签: javascript

所以我在我的介绍编程课中有一个非常具体的作业。我想用一个while循环和一个提示框来计算五个“游戏分数”的平均值。然后我必须将我的代码插入一个函数,然后使用一个按钮调用该函数。我一直在努力让它发挥作用,我很确定这可能是一个简单的错误让我退缩,这让人更加沮丧。

function Q1() {
  var sum = 0;
  var avg = 0;
  var sc1 = 0;
  var x = 1;

  alert("problem #2 find the average of five game scores");

  while (x < 5) {
    sc1 = prompt("enter the score from game # " + x);
    sum = parseFloat(sc1) + parseFloat(sum);
    avg = sum / x;
    x = x++;
    document.write(avg);
  }
};
<input type="button" value="run problem #2" onClick="Q1()" ;/>

4 个答案:

答案 0 :(得分:1)

您的代码中几乎没有错误。

  • 您从1开始只做4次,在4(x <5)
  • 结束
  • 移动应该在循环后运行一次的数学
  • 你没有parseFloat总和,你可以确定它已经是一个浮点数,它从0开始,你只添加浮点数。

您的代码已修复:

function Q1() {
  var scores = 0;
  var x = 1;
  alert("problem #2 find the average of five game scores");
  while (x <= 5) {
    scores += parseFloat(prompt("enter the score from game # " + x));
    x++;
  }
  document.write(scores/5);
}

或者:

function Q1() {
  var average = 0;
  alert("problem #2 find the average of five game scores");
  for (var x=0; x < 5; x++) 
    average += parseFloat(prompt("enter the score from game # " + x))/5;
  document.write(average);
}

更好的是,不要硬编码5

function Q1(games) {
  var average = 0;
  alert("problem #2 find the average of five game scores");
  for (var x=0; x < games; x++) 
    average += parseFloat(prompt("enter the score from game # " + x))/games;
  document.write(average);
}

答案 1 :(得分:0)

尝试这个找到5的平均值没有,你做了愚蠢的错误:

<html>
<body>
<input type="button" value="run problem #2" onClick="Q1()";/></br>
<script type= "text/javascript">
function Q1(){
var sum= 0;
var avg= 0;
var sc1= 0;
var x = 0;

alert ("problem #2 find the average of five game scores");

while(x < 5){
 sc1=prompt("enter the score from game # " + (x+1));    
     sum = parseFloat(sc1)+sum;
x++;  
}
 avg = sum/5;
 document.write(avg);
};
</script>
</body>
</html>

答案 2 :(得分:0)

变量在原件上使用的方式有点令人困惑,所以这就是我的建议。

HTML

<input type="button" value="run problem #2" onClick="Q1()"/>
<br/>

JS

function Q1(){
    var sum= 0;
    var avg= 0;
    var score= 0;
    var x = 1;
    var g = 5;

    alert ("problem #2 find the average of five game scores");

    while(x <= g){
        score=prompt("enter the score from game # "+x);    
        sum += parseFloat(score);
        x++;  
    }
    avg = sum /g;
    document.write("Average is " + avg);
}

答案 3 :(得分:0)

试试这个。

<script>
function Q1() {
  var sum = 0;
  var avg = 0;
  var sc1 = 0;
  var x = 0;

  alert("problem #2 find the average of five game scores");

  while (x < 5) {
    sc1 = prompt("enter the score from game # " + (x+1));
    sum = parseFloat(sc1) + parseFloat(sum);
    x++;
  }
 avg = sum / x;
 document.write(avg);
};
</script>