Home > Net >  GPA rater in C
GPA rater in C

Time:09-27

I'm trying to code a GPA rater. The problem: Write a C program that asks the user for their cumulative GPA in the range [0,4]. If the GPAenter code here is in:

  1. [3-4] you say, “Superb!”
  2. [2-3[ you say, “Good!”
  3. [1-2[ you say, “Hmm!”
  4. [0-1[ you say, “No comment!”

The program should display an error message and exit if the GPA entered exceeds 4 or less than 0.

Code:

#include <iostream>
using namespace std;
int main()
{
    double grade;

    cout << "Input your GPA: ";
    cin >> grade;
    cout << endl << endl;

    if (grade >= 0 && grade <= 4)
    {
        if (grade >= 0 && grade <= 1)
        {
            cout << "No comment!";
        }
        if (grade >= 1 && grade <= 2)
        {
            cout << "Hmm!";
        }
        if (grade >= 2 && grade <= 3)
        {
            cout << "Good!";
        }
        if (grade >= 3 && grade <= 4)
        {
            cout << "Superb!";
        }
    }
    else
    {
        cout << "Error : GPA is not in the specified range";
    }
    return 0;
}

I feel there is a more efficient way than mine. Is there? Thanks in advance

CodePudding user response:

There's probably a way to code golf it, but your code is clear. It does check things that you already know more than once.

For example, if (grade >= 0), then it still is on the next line. If it's not <= 1, then it is definitely > 1 -- you only need to check if it's <= 2 (with else if).

If you want to make something silly, you could something like this (after checking if grade is in range):

string m[4] = {"No comment!", "Hmm!", "Good!", "Superb!"};
cout << m[min(3, int(grade))];

You need to add:

#include <cmath>
#include <string>

It's fewer lines of code, but possibly not more efficient (you need to measure)

  •  Tags:  
  • c
  • Related