Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

javascript - Grading Students in JS with recursion - Range Error

I was trying to work on this hackerrank problem.

Every student receives a grade in the inclusive range from 0-100 to .

Any less than 38 is a failing grade. Sam is a professor at the university and likes to round each student's according to these rules:

If the difference between grade the and the next multiple of 5 is less than 3, round up to the next multiple of 5. If the value of grade is less than 38, no rounding occurs as the result will still be a failing grade.

Given the initial value of for each of Sam's students, write code to automate the rounding process.

My code is:

function gradingStudents(grades) {
  const roundup = y => y + 1;
{
   if ( grades < 38 || grades % 5 === 0) return grades;
   else if ( grades % 5 < 4 && grades % 5 !== 0) return roundup(grades);
}
{
   if (roundup % 5 === 0) return roundup;
   else { gradingStudents(roundup + 1) }
}
}

gradingStudents(38) // -> 39

I tried to use Math.ceil(grades) inside the variable roundup but output didnt change. So, when you invoke the function with a number that is not before a multiple of 5 (e.g. 43) it returns the proceeding number. However, if it is the number before a multiple of 5 it gives a range error. "maximum call stack size reached."

As far as I got, the code doesnt proceed to the second part. Even if it did, I am not sure if it would fetch the current value of the function roundup when dealing with if statements in the second block.

What do I dont get in here?

Also, this is actually meant for an array output but since I am a beginner I am pretty much okay with this one for the start as well :D .

question from:https://stackoverflow.com/questions/66059329/grading-students-in-js-with-recursion-range-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

function gradingStudents(grades) {  //input: 43
var finalGrade; 
if(grade < 38)              
    return grades;
else{
    var gradeDif = grades % 5; //3
    if(gradeDif > 3){
        return grades;
    }
    else {
        return grades + (5 - gradeDif); //Output: 45

    }
}

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...