Home > Mobile >  Finding the grade based on the best score
Finding the grade based on the best score

Time:04-15

So my program wants the user to input the number of students and their scores. Based on the best score it will follow this grading scheme:

  1. The score is > or = the best - 10 then the grade is A.
  2. The score is > or = the best - 20 then the grade is B.
  3. The score is > or = the best - 30 then the grade is C.
  4. The score is > or = the best - 40 then the grade is D.
  5. Anything else is an F

This is my code so far:

var readlineSync = require('readline-sync')


let scoreArray = []
let best = 0

students = readlineSync.question('Enter the number of students: ');

for (var x = 0; x < students; x  ){
 score = readlineSync.question('Enter Score: ')
 scoreArray.push(score);
}

for (var i = 0; i < scoreArray.length; i  ){
   var data = scoreArray[i];
   if(best < scoreArray[i]){
   best = scoreArray[i];
 }
   if(scoreArray[i] >= (best-10)){
     grade = 'A';
   }else if(scoreArray[i] >= (best-20)){
     grade = 'B';
   }else if(scoreArray[i] >= (best-30)){
     grade = 'C';
   }else if(scoreArray[i] >= (best-40)){
     grade = 'D';
   }else {
     grade = 'F';
  }
 console.log('Student '   i   ' score is '   scoreArray[i]  ' and grade is '     grade);

 }

When I run the code it sometimes displays the correct grade and sometimes it doesn't. It should display this:


  • Enter the number of students: 4
  • Enter Score: 40
  • Enter Score: 55
  • Enter Score: 70
  • Enter Score: 58
  • Student 0 score is 40 and grade is C. Student 1 score is 55 and grade is B. Student 2 score is 70 and grade is A. Student 3 score is 58 and grade is B.

Instead it displays the grades A,A,A,B.

CodePudding user response:

It looks like you're iterating over scoreArray and updating best along the way. You should first get the max score from scoreArray so you know the best to start with, and then iterate over scoreArray. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max for more info, but put var best = Math.max(...scoreArray); before your for loop, and then your conditional logic should work.

scoreArray = [49, 81, 72, 80, 81, 36, 58];
var best = Math.max(...scoreArray);

for (var i = 0; i < scoreArray.length; i  ) {
  var data = scoreArray[i];

  if (scoreArray[i] >= (best - 10)) {
    grade = 'A';
  } else if (scoreArray[i] >= (best - 20)) {
    grade = 'B';
  } else if (scoreArray[i] >= (best - 30)) {
    grade = 'C';
  } else if (scoreArray[i] >= (best - 40)) {
    grade = 'D';
  } else {
    grade = 'F';
  }

  console.log('Student '   i   ' score is '   scoreArray[i]   ' and grade is '   grade);

}

  • Related