如果无效函数内的循环不起作用
if loop inside a void function not working
所以我正在为 class 编写一个程序,并且我在函数定义内设置了一个 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;
}
}
请将 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
循环的更多信息:
所以我正在为 class 编写一个程序,并且我在函数定义内设置了一个 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;
}
}
请将 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
循环的更多信息: