【发布时间】:2015-10-09 20:08:32
【问题描述】:
我正在编写一个 GPA 计算器程序,我想将 char 的值更改为不同的数字。
例如,如果用户输入字母 a 或 A,则值将为 4。这就是我的程序的样子。如果我使用开关盒,我知道如何使它工作,但我想这样做。
char userInput;
char A, a = 4; // i want to change the value of A, a to 4
char B, b = 3; // i want to change the value of B, b to 3
char C, c = 2; // i want to change the value of C, c to 2
char D, d = 1; // i want to change the value of D, d to 1
char F, f = 0; // i want to change the value of F, f to 0
int count2 = 0;
int count3 = 0;
double gpa;
// the for loop is to make sure program will only run 3 times
for (int i=1; i<4;i++)
{
cout << "Test #" << i << ":" << endl;
cout << endl;
// the do while loop is being used to ensure that the user gets to
// input at least once.
do
{
cout << "Enter a Letter Grade (enter 'X' to exit): ";
cin >> userInput;
// the while loop is only being used for input valiation.
while (userInput!='A' && userInput!='a' && userInput!='B' &&
userInput!='b' && userInput!='C' && userInput!='c' &&
userInput!='D' && userInput!='d' && userInput!='F' &&
userInput!='f' && userInput !='X' && userInput !='x')
{
cout << "\n Invalid letter grade, please try again.\n";
cout << "\n Enter Letter Grade (enter 'X' to exit):";
cin >> userInput;
}
//line number 80 will add the values of the userInput together.
count2+=userInput;
// line 83 is a counter that holds the number of times the loop
// as excuted
count3++;
// line 88 will get a grade point average by dividing count3
// by count2
cout << fixed << showpoint << setprecision(2);
gpa = count2/count3;
} while(userInput !='X' && userInput!='x');
cout << "Total Grade Point: " << count2 << endl;
cout << "GPA: " << gpa << endl;
}
如果我的问题太模糊,请告诉我,以便我澄清。
【问题讨论】:
-
为什么要避免使用
switch语句?这是一个有效且直接的解决方案。 -
请参阅
std::tolower和std::toupper,因此您只需进行一半的比较。 -
原因是因为我们必须为这个项目制作流程图,而我在制作流程图时感到困惑,所以我想做我能理解的东西,而不是把半生不熟的想法放在一起。
-
由于您没有将
{紧跟在for语句之后,因此只会执行下一条语句4 次。 -
@ThomasMatthews 感谢您的更正,当我写在这里时,我放错了 {
标签: c++ char int type-conversion