并行数组,数字等级和字母等级

时间:2017-10-16 02:34:47

标签: c++

所以我创建了这个小程序,根据用户输入给出了一个字母等级。一切都很好,除非用户输入数字90或以上,它不会显示正确的字母:

#include <iostream>
using namespace std;

int main(int argc, char** argv) {

    int grade; // variable for user input

    int numberGrade[] = {90, 80, 70, 60, 0}; // initializing an array for numeric grades
    char letterGrade[] = {'A','B','C','D','F'}; // initializing an array for letter grades

    cout << "Enter the grade : ";
    cin >> grade;

    // for loop to output the correct letter based on the userInput
    for(int i = 0; i < 5; i++) {
        if(grade >= numberGrade[i] && grade < numberGrade[i-1])
            cout << "The grade is " << letterGrade[i] << endl;
    }
    return 0;
}

我怎样才能修改我的if声明,以便当用户输入数字90或以上时会显示正确的结果?

1 个答案:

答案 0 :(得分:0)

for循环中的if条件对于等级“A”不正确。这是因为i = 0的numberGrade [i-1]将是i = -1。因此,你没有得到答案!

这是代码:

int main() {
int grade; // variable for user input

int numberGrade[] = {90, 80, 70, 60, 0}; // initializing an array for numeric grades
char letterGrade[] = {'A','B','C','D','F'}; // initializing an array for letter grades

cout << "Enter the grade : ";
cin >> grade;
int flag = 0;
// for loop to output the correct letter based on the userInput
for(int i = 4; i >= 0 ; i--)
{
    if(grade >= numberGrade[i])
        continue;

    else
    {
        flag = 1;
        cout << "The grade is " << letterGrade[i+1] << endl;
        break;
    }

}
if(!flag)
    cout << "The grade is " << letterGrade[0] << endl;

return 0; }

我认为这是非常自我解释,我们只需添加一个标志并检查等级“A”条件。