C++ 函数,考试成绩为 0-100

c++ function with test scores 0-100

本文关键字:0-100 考试 函数 C++      更新时间:2023-10-16

my if 语句不是 100% 有效,我不确定我做错了什么。任何帮助将不胜感激,谢谢!这是我的函数

void DisplayStudentsInRange(const StudentType student[], int numStudents, int lownum, int highnum)
{
    cout <<"Enter two values from 0-100 for the range of test scores you want to view: ";
    cin >> lownum >> highnum;
    if ( lownum < 0 || highnum < 0 || lownum > highnum || lownum > 100 || highnum > 100)
    {
        cout <<"Please re-enter 2 values of test scores that you want to view from within the range 0-100";
        cin >> lownum >> highnum;
    }
    cout << endl << "List of students with scores in the range " << lownum << " to " << highnum << endl << endl;
    FormatNameScoreGrade(cout);

    for(int i = 0; i < numStudents; i++)
    {
        if(student[i].testScore >= lownum && student[i].testScore <= highnum)
        {
            cout << setw(20) << student[i].studentName << setw(10) << student[i].testScore << setw(10) << student[i].grade << endl;
        }
    }
    cout << endl;
}

不确定你在追求什么,但关于第一个if语句,你可能想将输入和验证放入一个循环中:

do {
    values = get_input();
} while (!values_are_valid());

我会在你的 if 语句中使用括号

if ( (lownum < 0) || (highnum < 0) || (lownum > highnum) || (lownum > 100) || (highnum > 100))

过去我没有这样做时,我遇到了问题。

请具体说明什么如果不是合适的也只是一个注释如果第二次输入的数据不正确,则第一个 if 将只工作一次您不会要求用户重新输入它,如果您想获得正确的输入你应该用一段时间替换你的第一个。

但总的来说,使用会更好

 Do {
     cout <<"Enter two values from 0-100 for the range of test scores you want to view: ";
     cin >> lownum >> highnum;
     }while( (lownum < 0) || (highnum < 0) || (lownum > highnum) || (lownum > 100) || (highnum > 100)); //statement
do

将按原样首次运行,然后如果输入不正确,while 语句将在输入正确后触发 do 部分。您可以编辑 couts 以类似于"输入/重新输入"等。