首页 > 解决方案 > void函数内的if循环不起作用

问题描述

所以我正在为一个类做一个程序,我在函数定义中设置了一个 if 循环来设置条目的参数。我应该只接受 0 到 10 之间的输入。但它只捕获小于 0 的数字。它不会捕获大于 10 的数字。

int main()
{
    float score1, score2, score3, score4, score5;
    cout << endl;
    cout << "Judge #1: " << endl;
    getJudgeData(score1);
    cout << "Judge #2: " << endl;
    getJudgeData(score2);
    cout << "Judge #3: " << endl;
    getJudgeData(score3);
    cout << "Score #4: " << endl;
    getJudgeData(score4);
    cout << "Score #5:  " << endl;
    getJudgeData(score5);

    calcScore(score1, score2, score3, score4, score5);

    return 0;
}

void getJudgeData (float &score)
{
    cin >> score;

    if(score < 0 || score > 10)
    {
        cout << "Error: Please enter a score between 0 and 10." << endl;
        cin >> score;
    }
}

标签: loopsvalidationinputparametersuser-input

解决方案


请将函数if中的条件更改为循环:getJudgeDatawhile

void getJudgeData (float &score)
{
    cin >> score;

    while (score < 0 || score > 10)
    {
        cout << "Error: Please enter a score between 0 and 10." << endl;
        cin >> score;
    }
}

否则条件只会被检查一次,意味着每个法官的第一次输入。如果我正确理解您的问题,这不是故意的。

请在此处找到有关while循环的更多信息:

尽管


推荐阅读