【问题标题】:I am having a hard time defining and displaying the average of an array of strings inputted by the user and displaying all number above 3.4我很难定义和显示用户输入的字符串数组的平均值并显示高于 3.4 的所有数字
【发布时间】:2019-12-14 14:39:30
【问题描述】:

该代码非常适合成绩或 GPA,我试图将用户输入到数组中的成绩的平均值 (GPAtotal / gpa.length) 显示出来。我还被要求展示一份优秀 GPA 的列表(定义为 GPA 超过3.4

我试过了:

  • 使用parseInt()将输入从数组中的字符串转换为数组中的整数。

  • 使用gpa.reduce((a,b) => a + b, 0) / gpa.length,但输入仍然是字符串。

我有将字符串转换为整数的转换类型。

var gpa = [];
var theGPA = "";
while (theGPA != "XXX")
{
    theGPA = prompt("Enter GPA or XXX to Stop");

    if (theGPA != "XXX") {
        gpa.push(theGPA);
    }
}

document.getElementById('output').innerHTML += "Average: " + "???" + "<br/>";
document.getElementById('output').innerHTML += "Outstanding GPA: " + "???";

当尝试显示平均值时,我会将用户估算的字符串作为一种解决方案,例如:

array: ["3.4", "4.0", "2.6"]
outputting: "Average: 4.04.32.6"

【问题讨论】:

  • 推入数组时可以使用gpa.push(+theGPA);将字符串转换为数字。阅读unary plus here。之后,gpa.reduce((a,b) =&gt; a + b, 0) / gpa.length 应该会满足您的期望。
  • 提示:map 使用parseInt,然后reduce 是该映射的结果。把大问题分解成小问题。 gpa.map(...).reduce(...) 作为模板。您还可以推送已使用 parseInt 处理的值。

标签: javascript arrays loops integer


【解决方案1】:

利用上述一些建议的代码

const gpa = ["3.4", "4.0", "2.6"];

const total = gpa.map(gpa => +gpa) // Map string to numeric (note the +)
    .reduce((avg, gpa) => avg += gpa); // Sum the gpa's
const average = total / gpa.length; // Compute average
console.log(`Average: ${average.toFixed(2)}`); // toFixed converts to a string, don't use it if you want to do math with the result!

【讨论】:

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