首页 > 解决方案 > 我的函数跳过了 C++ 中的循环参数

问题描述

我的 GetMark() 函数,它应该检查正确的范围,然后返回值,如果在我添加 SearchMark() 之前,当给定的参数超出接受的范围时,给定的数组会陷入无限循环函数它工作正常并且只循环直到用户最终输入给定范围(0 - 100)内的值,但现在在给出第一个超出范围的值后,无论输入什么,它都会循环,我将感谢任何建议。完整代码:

int GetMark(int ModuleIndex) //user input function
{
    bool help;
    if (ModuleIndex < 0 || ModuleIndex >100)
    {
        help = false;
        while (help != true)
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "hey, that's a invalid value, try again!" << endl;
            GetMark(ModuleIndex);
            if ((ModuleIndex > 0) &&( ModuleIndex < 101))
            {
                help = true;
            }
        }
    }

    return ModuleIndex;
}

int SearchMark(int A[], int a) //search grades array for numbers of specific grades
{
    int i = 0;
    int ii = 0;

    while (i < 12)
    {
        if (A[i] == a)
            ii++;
        i++;
    }
    cout << "Mark " << a << " was found: " << ii << " times" << endl;
    return 0;
}



int main()
{
    int marks[12]; 
    int i = 0;
    int sum = 0;
    int grades[12];

    while (i < 12)
    {
        cout << "enter mark (0 - 100): " << endl;
        cin >> marks[i];
        GetMark(marks[i]);
        sum = sum + marks[i];
        if (marks[i] > 69)
        {
            grades[i] = 1;
        }
        else if (marks[i] > 59 && marks[i] < 70)
        {
            grades[i] = 2;
        }
        else if (marks[i] > 49 && marks[i] < 60)
        {
            grades[i] = 22;
        }
        else if (marks[i] > 39 && marks[i < 50])
        {
            grades[i] = 3;
        }
        else if (marks[i] < 35)
        {
            grades[i] = 4;
        }
        i++;
    }
    sum = sum / 12;
    cout << "your average is: " << sum  << endl;




    if (sum > 69)
    {
        cout << "You passed with 1st!" << endl;
    }
    else if ((sum > 59) && (sum < 70))
    {
        cout << "You passed with 2i!" << endl;
    }
    else if ((sum > 49) && (sum < 60))
    {
        cout << "You passed with 2ii!" << endl;
    }
    else if ((sum > 39) && (sum < 50))
    {
        cout << "You passed with 3rd!" << endl;
    }
    else if (sum < 40)
    {
        cout << "Your average is too low! You failed." << endl;
    }


    i = 0;
    while (i < 12)
    {
        if (marks[i] < 35)
        {
            cout << "Referred in module " << i + 1 << " mark too low." << endl;
        }
        i++;
    }

    SearchMark(grades, 1);
    SearchMark(grades, 2);
    SearchMark(grades, 22);
    SearchMark(grades, 3);
    SearchMark(grades, 4);

    return 0;
}`

标签: c++functionloopsinfinite-loop

解决方案


该功能的功能过于复杂。只需在值错误时循环,并提示输入新值:

int GetMark(int ModuleIndex) {
    while (ModuleIndex < 0 || ModuleIndex > 100) {
        std::cout << "Invalid value.\n"
        std::cin >> ModuleIndex;
    }
    return ModuleIndex;
}

递归在理论分析中非常方便,但在实践中它几乎总是一个错误。


推荐阅读