输入提示数字的平均值

时间:2014-11-06 19:25:45

标签: javascript loops average

我在获取通过提示窗口输入的数字的平均值时遇到问题。我需要显示我到目前为止的数字,但我似乎无法将它们加在一起以获得平均值。

这是我目前的代码。

<html>
<body>

<script type="text/javascript">
function show_prompt() {
    i = 0;
    do {
        var number = prompt("Please Enter a Number");
        var number = parseInt(number);
        i++;

        document.write("Number: " + number);
        document.write("<br>");

    }
    while (i < 5);
}
show_prompt();
var avrg = number + number + number + number + number
document.write('Average of scores : ' + avrg);     
</script>   
</body>
</html>

2 个答案:

答案 0 :(得分:0)

请注意,您的var编号在show_prompt()范围内,在它之外是不可见的。

你需要让你的show_prompt函数不循环,并返回数字,并有另一个函数多次调用show_prompt,获取返回并计算平均值。此外,你的代码只是计算总和,而不是平均值

我不会向您显示确切的代码,但是这里的想法

calc_average:
  var sum=0;
  loop 5 times:
    sum = sum + show_prompt();
  average = sum/5;

show_prompt:
  var number = prompt('blah blah');
  return number

答案 1 :(得分:0)

你必须在函数内移动计算。你也可以做到更简单:

&#13;
&#13;
function show_prompt() {
  var i = 0;
  var sum = 0;//declare a variable to keep the sum of numbers
  do {
    var number = prompt("Please Enter a Number");
    sum += parseInt(number); //sum the numbers here
    i++;

    document.write("Number: " + number);
    document.write("<br>");

  }
  while (i < 5);

  document.write('Average of scores : ' + sum / i);//use the sum of the numbers divide by the the numbers the user enters
}
show_prompt();
&#13;
&#13;
&#13;

试图用错误评论你的旧代码:

&#13;
&#13;
function show_prompt() {
    i = 0;
    do {
        //there is no need to declare number twice
        //also you don't sum somewhere the numbers you get from the user
        var number = prompt("Please Enter a Number");
        var number = parseInt(number);
        i++;

        document.write("Number: " + number);
        document.write("<br>");

    }
    while (i < 5);
}
show_prompt();
//number is out of scope of function show_prompt so is undefined
var avrg = number + number + number + number + number
//to get an avg you have to divide the sum by the number
document.write('Average of scores : ' + avrg);
&#13;
&#13;
&#13;