我为一个类(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/