Grading system in C++

后端 未结 3 1978
故里飘歌
故里飘歌 2021-01-19 07:36

So this is my C++ question :

Write a program that translates a letter grade into a number grade. Letter grades are A, B, C, D and F, possibly followed by + or -. Th

3条回答
  •  伪装坚强ぢ
    2021-01-19 08:15

    I'd deal with each character in turn. You know that the first one should be a letter grade, so you look at that one first, and you could just use a switch statement like you've already got for that.

    uint value = 0;
    char grade_letter = grade[0];
    
    switch (grade_letter) {
        // assign value as appropriate
    }
    

    Then, if the second character exists, check if it's a + or a - and modify the value you got from the switch statement accordingly.

    if (grade.length() > 1) {
        char modifier = grade[1];
        switch (modifier) {
            case '+': value += 0.3;
            // etc.
        }
    }
    

    Before all that of course, you'll want to check for the special case of A+ and skip everything else.

    An alternative approach would be to replace the switch statements with lookups in a previously-prepared data structure, something like a std::map, which, even if the initialisation code prepared it from hardcoded data, would open the way to loading the grade information from a configuration file or database at some point in the future. Special-casing A+ in that case becomes slightly trickier though.

提交回复
热议问题