【发布时间】:2015-09-17 20:41:02
【问题描述】:
我为一个课程做这个作业,其中用户为每门课程输入 10 个成绩,将字母成绩转换为数值(例如“A”= 4)并将其乘以课程和课程的学分数将从那里计算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;
}
【问题讨论】:
-
您是否在询问如何验证和限制用户输入从“A”到“F”?
-
是的。我很抱歉没有具体说明。
标签: c++