【问题标题】:if loop inside a void function not workingvoid函数内的if循环不起作用
【发布时间】:2021-03-05 02:21:27
【问题描述】:

所以我正在为一个类做一个程序,我在函数定义中设置了一个 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;
    }
}

【问题讨论】:

  • 您的if 条件对我来说可以正常工作,但它还不是循环。因此它只要求正确输入一次。使用gcc version 8.3.0 测试。

标签: loops validation input parameters user-input


【解决方案1】:

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

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 循环的更多信息:

while

【讨论】:

  • @Jessica:请检查此答案是否对您有所帮助。如果是,请接受和/或投票。谢谢。
猜你喜欢
  • 2018-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
相关资源
最近更新 更多