如果 GPA 计算器的语句问题



一直在研究 GPA 计算器,我在运行程序时遇到的问题是,即使用户在被要求输入等级时输入等级"B">,GPA 仍然给出 5 的输出,这不应该是。

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
string course;
int courses;
int a_ = 1;
int units;
int gp = 0;
int tgp = 0;
int totalunits = 0;
string grade;
float gpa;
cout << "How many courses offered" << endl;
cin >> courses;
while (a_ <= courses){
cout << "Type the course code" << endl;
cin >> course;
cout << "Units allotted to the course" << endl;
cin >> units;
cout << "Input Grade " << endl;
cin >> grade;
if (grade == "A" || "a"){
gp = units * 5;
}
else if (grade == "B" || "b"){
gp = units * 4;
}
else if (grade == "C" || "c") {
gp = units * 3;
}
else if (grade == "D" || "d") {
gp = units * 2;
}
else if (grade == "E" || "e") {
gp = units * 1;
}
else if (grade == "F" || "f") {
gp = units * 0;
}
else {
cout << "Incorrect details, Re-Input them." << endl;
}

tgp = tgp + gp;
totalunits = totalunits + units;
++a_;
}
gpa = tgp/totalunits;
cout << tgp << endl;
cout << totalunits << endl;
cout << "Your GPA is : " << gpa << endl;
}

由于我收到的错误,将 switch 语句更改为 if 语句。

如果你强制大写,它将简化一切。

char grade;
cin >> grade;
grade = toupper(grade);
gp = units * ('F' - grade);

尝试一些转换函数,例如:

int points_from_grade(char grade) {
if (isupper(grade)) {
return 5 - (grade - 'A');
} else { // islower
return 5 - (grade - 'a');
}
}

关于C++字符,需要注意的一件有趣的事情是,它们有一个可用于数学运算的关联数值。

知道了这一点,您可以完成您打算做的事情的一种方法是取字符"A"(即 65(的十进制 ASCII 值并从中减去 60,这将为您提供该字母等级所需的整数值。

例如:

cout << 'A' - 60;

将输出整数"5"。

如果用户改为输入小写的"a",则需要取十进制 ASCII 值(即 97(并从中减去 92。

按照该架构,您应该能够确定需要进行哪些更改才能使程序按照您想要的方式工作。

作为参考,完整的 ASCII 表和描述可以在这里找到:https://www.asciitable.com/

您可以将switch语句更改为如下所示的内容:

// Relevant code parts
const int GRADE_A_POINTS = 5;
const int GRADE_B_POINTS = 4;
// etc.
char grade;
cin >> grade;
switch (grade) {
case 'A':
case 'a':
gp = units * GRADE_A_POINTS;
break;
case 'B':
case 'b':
gp = units * GRADE_B_POINTS;
break;
// etc.
}

最新更新