admin管理员组

文章数量:1024614

Given a function myGrading I need to return text that sent the letter grade corresponding to the given score.

  • (100 - 90) --> 'A'
  • (89 - 80) --> 'B'
  • (79 - 70) --> 'C'
  • (69 - 60) --> 'D'
  • (59 - 0) --> 'F'

  • Basically, if the given score is greater than 100 or less than 0, it should return 'INVALID SCORE'.

  • If the score is between the 0 and 2 (inclusive) of a given range, return the letter with a '-'
  • If the score is between the 8 and 9 (inclusive) of a given range, return the letter with a '+'
  • There are is no F+ and there is no F-.

So what I did is that I came up with an function using switch statement:

function myGrading(score) {
  var gscore;

  switch(true) {
    case (score <= 100 && score >= 90):
       gscore = 'A';
        break;
    case (score <= 89 && score >= 80):
        gscore = 'B';
         break;
    case (score <= 79 && score >= 70):
        gscore = 'C';
         break;
       case (score <= 69 && score >= 60):
        gscore = 'D';
         break;
    case (score <= 59 && score >= 0):
        gscore = 'F';
        break;

    case (score > 100 && score < 0):
        gscore = 'INVALID SCORE';
        break; 

     case (score <= 2 && score >= 0):
        gscore += '-';
        break; 

      case (score <= 9 && score >= 8):
        gscore += '+';
        break; 

    default:
      return 'INVALID SCORE';
}

  return gscore;
}

var output = convertScoreToGradeWithPlusAndMinus(91);
console.log(output); // --> MUST OUTPUT 'A-'

Right now the codes above doesn't display the right answer. Any idea what am I doing wrong?

Given a function myGrading I need to return text that sent the letter grade corresponding to the given score.

  • (100 - 90) --> 'A'
  • (89 - 80) --> 'B'
  • (79 - 70) --> 'C'
  • (69 - 60) --> 'D'
  • (59 - 0) --> 'F'

  • Basically, if the given score is greater than 100 or less than 0, it should return 'INVALID SCORE'.

  • If the score is between the 0 and 2 (inclusive) of a given range, return the letter with a '-'
  • If the score is between the 8 and 9 (inclusive) of a given range, return the letter with a '+'
  • There are is no F+ and there is no F-.

So what I did is that I came up with an function using switch statement:

function myGrading(score) {
  var gscore;

  switch(true) {
    case (score <= 100 && score >= 90):
       gscore = 'A';
        break;
    case (score <= 89 && score >= 80):
        gscore = 'B';
         break;
    case (score <= 79 && score >= 70):
        gscore = 'C';
         break;
       case (score <= 69 && score >= 60):
        gscore = 'D';
         break;
    case (score <= 59 && score >= 0):
        gscore = 'F';
        break;

    case (score > 100 && score < 0):
        gscore = 'INVALID SCORE';
        break; 

     case (score <= 2 && score >= 0):
        gscore += '-';
        break; 

      case (score <= 9 && score >= 8):
        gscore += '+';
        break; 

    default:
      return 'INVALID SCORE';
}

  return gscore;
}

var output = convertScoreToGradeWithPlusAndMinus(91);
console.log(output); // --> MUST OUTPUT 'A-'

Right now the codes above doesn't display the right answer. Any idea what am I doing wrong?

Share Improve this question asked Jun 23, 2017 at 0:49 user7435957user7435957 4
  • 1 i would use if here – Daniel A. White Commented Jun 23, 2017 at 0:50
  • 1 A better use of switch would be switch (Math.floor(score / 10)) – castletheperson Commented Jun 23, 2017 at 0:52
  • You've asked this already stackoverflow./questions/44691520/switch-ranges-of-output-js – A. L Commented Jun 23, 2017 at 0:56
  • @4castle: How is that? – user7435957 Commented Jun 23, 2017 at 1:03
Add a ment  | 

9 Answers 9

Reset to default 1

I came upon this while researching how to solve this. Sorry, I know this is an old thread but I hope by posting, perhaps I may get some views on my proposed solution to see if it's better, and if not what are its drawback. This should dynamically handle any distribution type passed to it as an object.

// An object with the letter grade as key and the floor value of the grade as its value
const distribution = {
  A: 90,
  B: 80,
  C: 70,
  D: 60,
  F: 0
};

const getGrade = (score, distribution, maxScore = 100, minScore = 0) => {

  // Handle edge cases
  if (score > maxScore || score < minScore) {
    return "Error";
  }
  // Get an array of the letter grades
  const grades = Object.keys(distribution);

  // Sort the grades in descending order of the floor score of each grade
  grades.sort((a, b) => distribution[b] - distribution[a]);

  // Since the grades are sorted, the first grade to be lower than the score will be the correct grade to return
  const grade = grades.find(grade => distribution[grade] <= score);

  // No + or - for bottom grade
  if (grade === grades[grades.length - 1]) {
    return grade
  } else if (score - distribution[grade] <= 2) { // check and return "-" grades
    return grade += "-"
  } else if (score - distribution[grade] >= 8) { // check and return "+" grades
    return grade += "+"
  } else { // return normal grades
    return grade
  }
};

If you consider the range 0-10 instead of 0-100, you can reduce your logic to:

function myGrading (score) {

  // Edge cases
  if (score < 0 || score > 100) return 'INVALID SCORE';
  if (score == 100) return 'A+';

  // Important values
  var decimal = score % 10;
  score = Math.floor(score / 10); // <- here we reduce the range to 0-9

              // 0    1    2    3    4    5    6    7    8    9
  var scores = ['F', 'F', 'F', 'F', 'F', 'F', 'D', 'C', 'B', 'A'];
  var grade = scores[score];

  if (grade != 'F') {
    if (decimal <= 2) grade += '-';
    else if (decimal >= 8) grade += '+';
  }

  return grade;
}

Hope it helps.

I went with a version similar to Washington. It gets goofy checking for edge cases.

let letter = ['F', 'F', 'F', 'F', 'F', 'F', 'D', 'C', 'B', 'A', 'A'];
let plumin = ['-', '-', '-', null, null, null, null, null, '+', '+'];
let major = num  => letter[Math.floor(num / 10)];
let minor = num => num === 100 ? '+' : (plumin[num % 10] || '');
let grade = num => major(num) ? major(num) + minor(num): major(num);
console.log(grade(-10));
console.log(grade(0));
console.log(grade(1));
console.log(grade(25));
console.log(grade(65));
console.log(grade(77));
console.log(grade(88));
console.log(grade(95));
console.log(grade(100));
console.log(grade(110));

here try this will put grade from for to paragraf

    <html>
   <body>
   <form action="#" method="GET" id="forma">
   <input type="text" id="grade" name="grade"/>
   <input type="submit" id="submit" value="PRESS" onclick="myGrading(this);"/>
   </form>
   <p id='grades'></p>
   </body>
   </html>
   <script>



   function myGrading() {
     var gscore;
     var score = document.getElementById('grade').value
     switch(true) {
case (score <= 100 && score >= 90):
   gscore = 'A';
    break;
case (score <= 89 && score >= 80):
    gscore = 'B';
     break;
case (score <= 79 && score >= 70):
    gscore = 'C';
     break;
   case (score <= 69 && score >= 60):
    gscore = 'D';
     break;
case (score <= 59 && score >= 0):
    gscore = 'F';
    break;

case (score > 100 && score < 0):
    gscore = 'INVALID SCORE';
    break; 

 case (score <= 2 && score >= 0):
    gscore += '-';
    break; 

  case (score <= 9 && score >= 8):
    gscore += '+';
    break; 

default:
  return 'INVALID SCORE';
   }
          document.getElementById('grades').innerHTML=gscore;


   }




   </script>

You need to take logic to append signs out of the switch box as they will never get executed there. refactor your code as below:

function myGrading(score) {
  var gscore;

  switch(true) {
    case (score <= 100 && score >= 90):
       gscore = 'A';
        break;
    case (score <= 89 && score >= 80):
        gscore = 'B';
         break;
    case (score <= 79 && score >= 70):
        gscore = 'C';
         break;
       case (score <= 69 && score >= 60):
        gscore = 'D';
         break;
    case (score <= 59 && score >= 0):
        gscore = 'F';
        break;

    case (score > 100 && score < 0):
        gscore = 'INVALID SCORE';
        break; 

    default:
      return 'INVALID SCORE';
  }
  
  var last_digit = score%10;
  if(last_digit <=2 && last_digit >= 0 && score != 100){
    gscore+='-';
  }
  else if((last_digit <=9 && last_digit >= 7) || score == 100){
    gscore+='+';
  }

  return gscore;
};

console.log(myGrading(91));
console.log(myGrading(75));
console.log(myGrading(100));

function convertScoreToGradeWithPlusAndMinus(score) {
  var grade = ''; //creating a variable keeps it cleaner.
  var scoreStr = score.toString(); //convert the score number into a string. This allows us to access indexes.

  if(score > 100 || score < 0) return 'INVALID SCORE'; //set the edge case first.

  if(score === 100) grade = 'A';
    else if(score >= 90) grade = 'A';
      else if(score >= 80) grade = 'B';
        else if(score >= 70) grade = 'C';
          else if(score >= 60) grade = 'D';
            else if(score >= 0) grade = 'F';
              
  
  if(grade !== 'F'){ //Negate 'F' before distributing + or - to letter grades.
    if(scoreStr.substring(1) >= 8 || score === 100) {
      grade += '+';
    } else if(scoreStr.substring(1) <=2) {
      grade += '-';
    }
  }

  return grade;
}
var output = convertScoreToGradeWithPlusAndMinus(91);
console.log(output); // --> 'A-'

This is how I was able to solve the same problem.

function getScore(score) {
return 
 (score >=90 && score <=100) ? "A":
 (score >=80 && score <=89)  ? "B":
 (score >=70 && score <=79)  ? "C":
 (score >=60 && score <=69)  ? "D":
 (score <=60 && score >=0)   ? "E":
        "Nota Inválida"
}

console.log(getScore(100))
You can try the following code for outputting the grades:
    
    
    
    let mark = 97; 
    
    if (mark <= 100 && mark >= 90){
          console.log("Gread A+")
    }
    
    else if(mark <= 89 && mark >= 80){
          console.log("Gread A")
    }
    
    else if(mark <= 79 && mark >= 70){
          console.log("Gread B")
    }
    
    else if(mark <= 69 && mark >= 60){
          console.log("Gread C")
    }
    
    else if(mark < 60 ){
          console.log("Gread F")
    }

let inPut = prompt("What is your score?", )

    if (inPut <= 100 && inPut >= 90) {
        alert('Your grade is A');
    } else if (inPut <= 89 && inPut >= 70) {
        alert('Your grade is B')
    } else if (inPut <= 69 && inPut >= 60) {
        alert('Your grade is C')
    } else if (inPut <= 59 && inPut >= 50) {
        alert('Your grade is D')
    } else if (inPut <= 49 && inPut >= 0) {
        alert('Your grade is F')
    } else(
        alert('Invalid Score')
    );

Given a function myGrading I need to return text that sent the letter grade corresponding to the given score.

  • (100 - 90) --> 'A'
  • (89 - 80) --> 'B'
  • (79 - 70) --> 'C'
  • (69 - 60) --> 'D'
  • (59 - 0) --> 'F'

  • Basically, if the given score is greater than 100 or less than 0, it should return 'INVALID SCORE'.

  • If the score is between the 0 and 2 (inclusive) of a given range, return the letter with a '-'
  • If the score is between the 8 and 9 (inclusive) of a given range, return the letter with a '+'
  • There are is no F+ and there is no F-.

So what I did is that I came up with an function using switch statement:

function myGrading(score) {
  var gscore;

  switch(true) {
    case (score <= 100 && score >= 90):
       gscore = 'A';
        break;
    case (score <= 89 && score >= 80):
        gscore = 'B';
         break;
    case (score <= 79 && score >= 70):
        gscore = 'C';
         break;
       case (score <= 69 && score >= 60):
        gscore = 'D';
         break;
    case (score <= 59 && score >= 0):
        gscore = 'F';
        break;

    case (score > 100 && score < 0):
        gscore = 'INVALID SCORE';
        break; 

     case (score <= 2 && score >= 0):
        gscore += '-';
        break; 

      case (score <= 9 && score >= 8):
        gscore += '+';
        break; 

    default:
      return 'INVALID SCORE';
}

  return gscore;
}

var output = convertScoreToGradeWithPlusAndMinus(91);
console.log(output); // --> MUST OUTPUT 'A-'

Right now the codes above doesn't display the right answer. Any idea what am I doing wrong?

Given a function myGrading I need to return text that sent the letter grade corresponding to the given score.

  • (100 - 90) --> 'A'
  • (89 - 80) --> 'B'
  • (79 - 70) --> 'C'
  • (69 - 60) --> 'D'
  • (59 - 0) --> 'F'

  • Basically, if the given score is greater than 100 or less than 0, it should return 'INVALID SCORE'.

  • If the score is between the 0 and 2 (inclusive) of a given range, return the letter with a '-'
  • If the score is between the 8 and 9 (inclusive) of a given range, return the letter with a '+'
  • There are is no F+ and there is no F-.

So what I did is that I came up with an function using switch statement:

function myGrading(score) {
  var gscore;

  switch(true) {
    case (score <= 100 && score >= 90):
       gscore = 'A';
        break;
    case (score <= 89 && score >= 80):
        gscore = 'B';
         break;
    case (score <= 79 && score >= 70):
        gscore = 'C';
         break;
       case (score <= 69 && score >= 60):
        gscore = 'D';
         break;
    case (score <= 59 && score >= 0):
        gscore = 'F';
        break;

    case (score > 100 && score < 0):
        gscore = 'INVALID SCORE';
        break; 

     case (score <= 2 && score >= 0):
        gscore += '-';
        break; 

      case (score <= 9 && score >= 8):
        gscore += '+';
        break; 

    default:
      return 'INVALID SCORE';
}

  return gscore;
}

var output = convertScoreToGradeWithPlusAndMinus(91);
console.log(output); // --> MUST OUTPUT 'A-'

Right now the codes above doesn't display the right answer. Any idea what am I doing wrong?

Share Improve this question asked Jun 23, 2017 at 0:49 user7435957user7435957 4
  • 1 i would use if here – Daniel A. White Commented Jun 23, 2017 at 0:50
  • 1 A better use of switch would be switch (Math.floor(score / 10)) – castletheperson Commented Jun 23, 2017 at 0:52
  • You've asked this already stackoverflow./questions/44691520/switch-ranges-of-output-js – A. L Commented Jun 23, 2017 at 0:56
  • @4castle: How is that? – user7435957 Commented Jun 23, 2017 at 1:03
Add a ment  | 

9 Answers 9

Reset to default 1

I came upon this while researching how to solve this. Sorry, I know this is an old thread but I hope by posting, perhaps I may get some views on my proposed solution to see if it's better, and if not what are its drawback. This should dynamically handle any distribution type passed to it as an object.

// An object with the letter grade as key and the floor value of the grade as its value
const distribution = {
  A: 90,
  B: 80,
  C: 70,
  D: 60,
  F: 0
};

const getGrade = (score, distribution, maxScore = 100, minScore = 0) => {

  // Handle edge cases
  if (score > maxScore || score < minScore) {
    return "Error";
  }
  // Get an array of the letter grades
  const grades = Object.keys(distribution);

  // Sort the grades in descending order of the floor score of each grade
  grades.sort((a, b) => distribution[b] - distribution[a]);

  // Since the grades are sorted, the first grade to be lower than the score will be the correct grade to return
  const grade = grades.find(grade => distribution[grade] <= score);

  // No + or - for bottom grade
  if (grade === grades[grades.length - 1]) {
    return grade
  } else if (score - distribution[grade] <= 2) { // check and return "-" grades
    return grade += "-"
  } else if (score - distribution[grade] >= 8) { // check and return "+" grades
    return grade += "+"
  } else { // return normal grades
    return grade
  }
};

If you consider the range 0-10 instead of 0-100, you can reduce your logic to:

function myGrading (score) {

  // Edge cases
  if (score < 0 || score > 100) return 'INVALID SCORE';
  if (score == 100) return 'A+';

  // Important values
  var decimal = score % 10;
  score = Math.floor(score / 10); // <- here we reduce the range to 0-9

              // 0    1    2    3    4    5    6    7    8    9
  var scores = ['F', 'F', 'F', 'F', 'F', 'F', 'D', 'C', 'B', 'A'];
  var grade = scores[score];

  if (grade != 'F') {
    if (decimal <= 2) grade += '-';
    else if (decimal >= 8) grade += '+';
  }

  return grade;
}

Hope it helps.

I went with a version similar to Washington. It gets goofy checking for edge cases.

let letter = ['F', 'F', 'F', 'F', 'F', 'F', 'D', 'C', 'B', 'A', 'A'];
let plumin = ['-', '-', '-', null, null, null, null, null, '+', '+'];
let major = num  => letter[Math.floor(num / 10)];
let minor = num => num === 100 ? '+' : (plumin[num % 10] || '');
let grade = num => major(num) ? major(num) + minor(num): major(num);
console.log(grade(-10));
console.log(grade(0));
console.log(grade(1));
console.log(grade(25));
console.log(grade(65));
console.log(grade(77));
console.log(grade(88));
console.log(grade(95));
console.log(grade(100));
console.log(grade(110));

here try this will put grade from for to paragraf

    <html>
   <body>
   <form action="#" method="GET" id="forma">
   <input type="text" id="grade" name="grade"/>
   <input type="submit" id="submit" value="PRESS" onclick="myGrading(this);"/>
   </form>
   <p id='grades'></p>
   </body>
   </html>
   <script>



   function myGrading() {
     var gscore;
     var score = document.getElementById('grade').value
     switch(true) {
case (score <= 100 && score >= 90):
   gscore = 'A';
    break;
case (score <= 89 && score >= 80):
    gscore = 'B';
     break;
case (score <= 79 && score >= 70):
    gscore = 'C';
     break;
   case (score <= 69 && score >= 60):
    gscore = 'D';
     break;
case (score <= 59 && score >= 0):
    gscore = 'F';
    break;

case (score > 100 && score < 0):
    gscore = 'INVALID SCORE';
    break; 

 case (score <= 2 && score >= 0):
    gscore += '-';
    break; 

  case (score <= 9 && score >= 8):
    gscore += '+';
    break; 

default:
  return 'INVALID SCORE';
   }
          document.getElementById('grades').innerHTML=gscore;


   }




   </script>

You need to take logic to append signs out of the switch box as they will never get executed there. refactor your code as below:

function myGrading(score) {
  var gscore;

  switch(true) {
    case (score <= 100 && score >= 90):
       gscore = 'A';
        break;
    case (score <= 89 && score >= 80):
        gscore = 'B';
         break;
    case (score <= 79 && score >= 70):
        gscore = 'C';
         break;
       case (score <= 69 && score >= 60):
        gscore = 'D';
         break;
    case (score <= 59 && score >= 0):
        gscore = 'F';
        break;

    case (score > 100 && score < 0):
        gscore = 'INVALID SCORE';
        break; 

    default:
      return 'INVALID SCORE';
  }
  
  var last_digit = score%10;
  if(last_digit <=2 && last_digit >= 0 && score != 100){
    gscore+='-';
  }
  else if((last_digit <=9 && last_digit >= 7) || score == 100){
    gscore+='+';
  }

  return gscore;
};

console.log(myGrading(91));
console.log(myGrading(75));
console.log(myGrading(100));

function convertScoreToGradeWithPlusAndMinus(score) {
  var grade = ''; //creating a variable keeps it cleaner.
  var scoreStr = score.toString(); //convert the score number into a string. This allows us to access indexes.

  if(score > 100 || score < 0) return 'INVALID SCORE'; //set the edge case first.

  if(score === 100) grade = 'A';
    else if(score >= 90) grade = 'A';
      else if(score >= 80) grade = 'B';
        else if(score >= 70) grade = 'C';
          else if(score >= 60) grade = 'D';
            else if(score >= 0) grade = 'F';
              
  
  if(grade !== 'F'){ //Negate 'F' before distributing + or - to letter grades.
    if(scoreStr.substring(1) >= 8 || score === 100) {
      grade += '+';
    } else if(scoreStr.substring(1) <=2) {
      grade += '-';
    }
  }

  return grade;
}
var output = convertScoreToGradeWithPlusAndMinus(91);
console.log(output); // --> 'A-'

This is how I was able to solve the same problem.

function getScore(score) {
return 
 (score >=90 && score <=100) ? "A":
 (score >=80 && score <=89)  ? "B":
 (score >=70 && score <=79)  ? "C":
 (score >=60 && score <=69)  ? "D":
 (score <=60 && score >=0)   ? "E":
        "Nota Inválida"
}

console.log(getScore(100))
You can try the following code for outputting the grades:
    
    
    
    let mark = 97; 
    
    if (mark <= 100 && mark >= 90){
          console.log("Gread A+")
    }
    
    else if(mark <= 89 && mark >= 80){
          console.log("Gread A")
    }
    
    else if(mark <= 79 && mark >= 70){
          console.log("Gread B")
    }
    
    else if(mark <= 69 && mark >= 60){
          console.log("Gread C")
    }
    
    else if(mark < 60 ){
          console.log("Gread F")
    }

let inPut = prompt("What is your score?", )

    if (inPut <= 100 && inPut >= 90) {
        alert('Your grade is A');
    } else if (inPut <= 89 && inPut >= 70) {
        alert('Your grade is B')
    } else if (inPut <= 69 && inPut >= 60) {
        alert('Your grade is C')
    } else if (inPut <= 59 && inPut >= 50) {
        alert('Your grade is D')
    } else if (inPut <= 49 && inPut >= 0) {
        alert('Your grade is F')
    } else(
        alert('Invalid Score')
    );

本文标签: switch statementoutputting grades in JavaScriptStack Overflow