gpt4 book ai didi

javascript - 如何计算平均成绩

转载 作者:行者123 更新时间:2023-11-30 10:59:48 28 4
gpt4 key购买 nike

我是 JavaScript 的新手,似乎无法弄清楚为什么我的最后一个函数没有做它应该做的事情,即使用用户输入的成绩(数字)的平均值来返回字母成绩。

我的第一个函数正常工作,我的第二个函数编写正确(我认为)但是对于我的第三个函数我不确定我做错了什么,因为当我测试运行时没有任何显示。

这是我在代码中所做的:

var grades = [];
var totalSum = 0;


function myFunction() {
for (var i = 0; i < 5; i++) {
grades[i] = parseInt(prompt("Enter a Grade: "));
document.getElementById("gradeInput").innerHTML += grades[i] + " ";
}
}


function gradeAverage() {
for (var i = 0; i < grades.length; i++) {
totalSum += grades[i];
var average = totalSum / grades.length;
}
}


function letterGrade() {

if (totalSum <= 90) {
document.getElementById("finalGrade").innerHTML += average + " A";
} else if (totalSum <= 80) {
document.getElementById("finalGrade").innerHTML += average + " B";
} else if (totalSum <= 70) {
document.getElementById("finalGrade").innerHTML += average + " C";
} else if (totalSum <= 60) {
document.getElementById("finalGrade").innerHTML += average + " D";
} else {
document.getElementById("finalGrade").innerHTML += average + " F";
}
}

myFunction();
gradeAverage();
letterGrade();

最佳答案

你需要将 average 变量作为全局变量,并像这样在你的 letterGrade() 中进行一些修复:

添加:如果分数为 90 或以下,letterGrade() 将始终返回 A

var grades = [];
var totalSum = 0;
var average = 0

// function to read five values from series of prompts stored in array
function myFunction() {
for (var i = 0; i < 5; i++) {
grades[i] = parseInt(prompt("Enter a Grade: "));
document.getElementById("gradeInput").innerHTML += grades[i] + " ";
}
}

// function to calculate the average of the five entered grades and store it in a variable
function gradeAverage() {
for (var i = 0; i < grades.length; i++) {
totalSum += grades[i];
average = totalSum / grades.length;
}
}

// funtion to use the average of entered grades to determine letter grade that it will return to the user
function letterGrade() {

if (average >= 90 && average <= 100) {
document.getElementById("finalGrade").innerHTML += average + " A";
} else if (average >= 80 && average <= 89) {
document.getElementById("finalGrade").innerHTML += average + " B";
} else if (average >= 70 && average <= 79) {
document.getElementById("finalGrade").innerHTML += average + " C";
} else if (average >= 60 && average <= 69) {
document.getElementById("finalGrade").innerHTML += average + " D";
} else if (average <= 59) {
document.getElementById("finalGrade").innerHTML += average + " F";
}
}

myFunction();
gradeAverage();
letterGrade();
<p id="gradeInput">You entered the following grades: </p>
<p id="finalGrade">Your grade average is: </p>

关于javascript - 如何计算平均成绩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58315874/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com