dimanche 11 octobre 2020

Problem with Javascript function not returning total sum in a for loop with if conditions

I am writing pure javascript without any HTML and I am having trouble with one of my functions that would need to return the total "course points."

The program consists of prompting the user the # of course taken followed by the grade received which is pushed in the "grades" array. The function calculateCP will allow it to reiterate every element of the array and is suppose to give me the total course points given the following if conditions.

Please help why my function isn't working! The output is returning only the first element of the array, not the total sum of all elements.

calculateCP = () => {
  let coursePoints;
  let total = 0;

  for (let i = 0; i < grades.length; i++) {
    if (grades[i] >= 90) {
      coursePoints = 4;
    } else if (grades[i] >= 80 && grades[i] < 90) {
      coursePoints = 3;
    } else if (grades[i] >= 70 && grades[i] < 80) {
      coursePoints = 2;
    } else if (grades[i] >= 60 && grades[i] < 70) {
      coursePoints = 1;
    } else if (grades[i] < 60) {
      coursePoints = 0;
    }
    return total = total + coursePoints;
  }
}
  const grades = [];

  let noOfCourses = parseInt(prompt("Please enter # of courses taken: "));
  console.log("\n")

  for (let i = 0; i < noOfCourses; i++) {
    grades.push(prompt('Enter grade recieved '));
  }
  console.log(calculateCP());
}

Aucun commentaire:

Enregistrer un commentaire