c++ - 我该如何改进这个 GPA 计算代码?

标签 c++

我为一个类(class)完成了这项作业,其中用户为每门类(class)输入 10 个等级,将字母等级转换为数值(例如“A”= 4)并将其乘以类(class)和项目的学分数会从那里计算GPA。它工作得很好,但我想改进这一点,以便当用户输入等级时,它不会是除“A”、“B”、“C”、“D”和“F”之外的任何随机值。

有什么想法吗?我知道涉及循环,但我不知道从哪里开始。这是我的代码:

 #include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

int main() {
    //declare variables to store grades, credits, courses and numeric grades
    string letterGrade[10]; //this variable is used to store the user's grades so that we can turn them into numbers
    double numericGrade[10];
    string courses[10] = { "MATH100", "ENG100", "BIO250", "ITM100", "CIS250", "HIST101", "CALC100", "SCI201", "SOC110", "PHY100" };
    int creditForCourses[10] = { 5, 3, 4, 3, 3, 3, 4, 3, 3, 4 };
    double gpa = 0.00;
    int i;

    //this for loop asks the user to enter a grade for each of their courses
    for (i = 0; i < 10; i++) {
        cout << "Enter grade for: " << courses[i] << endl;
        cin >> letterGrade[i];
        }


        //the loop converts the letter grade into a numeric value
    for (i = 0; i < 10; i++) {
        if (letterGrade[i] == "A") {
            numericGrade[i] = 4; //for each if statement, turn a specific letter grade into a value and store it into numericGrade
            }
            else
            if (letterGrade[i] == "B") {
            numericGrade[i] = 3.5;
            }
            else
            if (letterGrade[i] == "C") {
            numericGrade[i] = 3;
            }
            else
            if (letterGrade[i] == "D") {
            numericGrade[i] = 2.5;
            }
            else
            if (letterGrade[i] == "F") {
            numericGrade[i] = 0;
            }
    }





        //calculate gpa by multipling each grade value and each credit from courses
        for (i = 0; i < 10; i++) {
            gpa += (numericGrade[i] * creditForCourses[i]);
        }

        //divide each numeric grade and credit and divide it by 35 (the total amount of credits)
        gpa /= 35;

        //print overall gpa for the student
        cout << "Your GPA is: " << gpa << endl;

    return 0;
}

最佳答案

在要求用户为他们的每门类(class)输入成绩的 for 循环中,您可以限制用户输入有效成绩。以下是可能有效的代码。

for (i = 0; i < 10; i++)
{
    cout << "Enter grade for: " << courses[i] << endl;
    char grd;
    cin>>grd;
    if(grd=='A'||grd=='B'||grd=='C'||grd=='D'||grd=='F')
      letterGrade[i] = grd;
    else
    {
        cout<<"Please enter valid grade(A, B, C, D, F)"<<endl;
        i--;
    }
}

关于c++ - 我该如何改进这个 GPA 计算代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32639599/

相关文章:

c++ - 标准化 -1 和 1 之间的负数或正数?

c++ - 如何使用 std::visit 将 std::variant 的值转换为 std::string

c++ - 以纵横比旋转二维 vector

c++ - 将 Window::set_title 与 gtkmm 一起使用时窗口标题截断

c++ - OpenCV 预期的构造函数、析构函数或类型转换

c++ - 如何避免编译器优化某些操作?

C++如何将函数连接到程序?

c++ - 无法解决有关此代码的难题

c++ - 日志文件中特定用户的访问页面

c++ - 第三方库应该放在哪里?