简体   繁体   中英

how can I round of the grading system using C++

Every student receives a grade in the inclusive range from 0 to 100. Any grade less than 40 is a failing grade. Sam is a professor at the university and likes to round each student's grade according to these rules:

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

Sample Input

4 73 67 38 33

Sample Output

75 67 40 33

here is the code I have made, can anyone tell me what is wrong in this, coz it just pass 11/12 test cases.

vector<int> gradingStudents(vector<int> grades) {
    for(int i=0;i<grades.size();i++)
    { 
        if((grades[i])<38)
            break;
        if((grades[i]%5) >= 3)
            grades[i]=grades[i]+ (5-(grades[i]%5))
    }
    return grades;

}


Here is the final working code:

vector<int> gradingStudents(vector<int> grades) {
    for(int i=0;i<grades.size();i++)
    { 
         if((grades[i])<38)
           continue;
        if((grades[i]%5) >= 3)
            grades[i]=grades[i]+ (5-(grades[i]%5))
    }
    return grades;

You break out of your loop as soon as you found a grade below 38 , and don't even look at the rest of the grades.

You need to skip those elements by using continue; :

    if((grades[i])<38)
        continue;

Just noticed that you pass your vector<int> grades argument by value, so all changes you make to it in that function are not visible outside of it. You need to pass by reference:

vector<int> gradingStudents(vector<int>& grades) {

Incorporating john's advice, using more modern range for loop and eliminationg redundant return of the modified in-place passed in vector (that is, if you don't need to preserve the original):

void gradingStudents(vector<int>& grades) {
  for (auto& grade : grades)
  {
    if (grade > 37 && (grade % 5) >= 3)
      grade = grade + (5 - (grade % 5));
  }
}

int main()
{
  vector<int> grades = { 73, 67, 38, 33 };
  gradingStudents(grades);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM