我有一个作业,需要介绍字母等级。没有加号或减号的数据类型将不会输出正确的值。值“A”正确输出,但“A-”不正确。代码如下:
#include <iostream>
using namespace std;
int main()
{
char letGrade;
cout << "What is your letter grade? ";
cin >> letGrade;
if (letGrade == 'A')
cout << "The numeric value is 4.0\n";
else if (letGrade == 'A-')
cout << "The numeric value is 3.5\n";
cout << "That's an invalid numeric value.\n";
return 0;
}
最佳答案
输入的是A-
,该行
cin >> letGrade;
不会将
-
部分读取为letGrade
。它将仅读取A
部分。将
letGrade
更改为std::string
。另外,将比较语句更改为字符串。std::string letGrade;
cout << "What is your letter grade? ";
cin >> letGrade;
if (letGrade == "A")
cout << "The numeric value is 4.0\n";
else if (letGrade == "A-")
cout << "The numeric value is 3.5\n";