【问题标题】:How do you write a program in javascript that asks the user to enter a list of numbers, and then find the average of the numbers你如何用javascript编写一个程序,要求用户输入一个数字列表,然后找到数字的平均值
【发布时间】:2019-08-24 17:23:06
【问题描述】:

我无法让这个程序输出用户输入的提示数字的平均值。我还应该如何编码?任何帮助将不胜感激。

var gpas = [];
var gp;
var total = 0;
let count = 0;
var max = 0;
var min = 0;
var out = "";
while (i != "XXX") {
    var i = prompt("Enter a gpa or XXX to Stop");
    if (i != "XXX") {
        gpas.push(i);
    }
}
for (var i = 0; i < gpas.length; i++) {
    out += gpas[i];
    out += "<br/>";
}
count++;
total += gpas[i];
var avg = total / count;
out += avg;
document.getElementById('output').innerHTML += out + "<br/>";

输出显示“NaN”而不是有效数字。

【问题讨论】:

  • 请使用gpas.push(parseInt(i));
  • for 循环之后的一些代码似乎属于for 循环。
  • 感谢您的回答。 @FelixKling,哪些代码应该属于里面?

标签: javascript arrays average


【解决方案1】:

您只能使用一个变量来保存输入数字的总和,然后将其除以输入的总数。

第一种方法无限循环

第一种方法是您正在使用的方法。基本上,只要我们没有得到字符串"XXX",我们就会要求一个新号码。

/** 
* @const output the span where to print the average.
**/
const output = document.getElementById('output');

/**
* @var avg stores the sum of the entered numbers.
* @var i keeps track of the number of numbers entered.
**/
let sum = 0,
  i = 0;
  
/** basically while true increment i **/
while (1 && ++i) {
  /** ask for a number or "XXX" to exit **/
  const n = prompt(`Enter a number or enter "XXX" to exit :`, 0);
  /** if "XXX" is entered break the loop (the only way to break that infinite loop) **/
  if(n == 'XXX') break;
  /** if something else than "XXX" is entered try to cast it to a float  **/
  sum += parseFloat(n);
}

/** print the average **/
output.textContent = (sum / (i - 1)).toFixed(2); /** why dividing by "i - 1" and not only "i" is because "i" is incremented even when we enter "XXX" **/
&lt;div&gt;average: &lt;span id="output"&gt;&lt;/span&gt;&lt;/div&gt;

这种方法对用户不友好(除非输入"XXX",否则无法退出循环)并且可能会消耗大量资源。

第二种方法固定数量的数字

这种方法要求用户输入他想输入的数字,然后我们要求他输入与他之前输入的数字一样多的数字。

const output = document.getElementById('output');

/**
* @var n the number of numbers the user is going to type.
* @var sum the sum of these numbers.
* @var i a counter used to exit the loop when we reach "n" nummbers typed. 
**/
let n = prompt('How many element do you want to enter ?', 2),
  sum = 0,
  i = 0;
  
/** while i + 1 < n and no need to manually break the loop **/
while (i++ < n) sum += parseFloat(prompt(`Enter a number (${i} remaining) :`, 0));

output.textContent = (sum / n).toFixed(2); /** now we know how many numbers entered from the beging thanks to the variable "n" **/
&lt;div&gt;average: &lt;span id="output"&gt;&lt;/span&gt;&lt;/div&gt;

parseFloat 用于将用户输入的数字(实际上是字符串)解析为浮点数。

toFixed 用于计算平均值时只有两位小数。

【讨论】:

  • 非常感谢,这确实做到了。
【解决方案2】:
while (i != "XXX") {
    var i = prompt("Enter a gpa or XXX to Stop");
    if (i != "XXX") {
        gpas.push(parseInt(i)); // we need string to number with `parseInt`
    }
}

【讨论】:

    【解决方案3】:

    感谢所有做出贡献的人。通过应用给出的一些建议,我能够让它发挥作用。我还注意到下面的代码也可以工作:

     var gpas = [];
     var gp;
    var out = "";
    while (i != "XXX")
    {
    var i = prompt("Enter a gpa or XXX to Stop");
    if(i != "XXX"){
    gpas.push(parseInt(i));
    }
    }  
         let sum = gpas.reduce((a, b) => {
     return a + b;
    }); 
    
    sum;
    var avg = (sum/gpas.length);
    document.getElementById('output').innerHTML += "average =" + avg + "<br/>";
    </script>````
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多