我还是C ++程序的新手,我似乎还不了解break语句的用法。这里的编码是否正确以打破循环?
int validateHours(int nohours)
{
while (nohours < 0 || nohours > 150)
{
cout << "Error! Hours cannot be negative or exceed 150" << endl;
cin >> nohours;
break;
}
}
答案 0 :(得分:0)
由于您已经在while
循环的开始处添加了条件,因此这里不需要break
。
您可以像这样使用break
。
int validateHours(int nohours)
{
while (true) // Removed condition and loop is foreever ture
{
cout << "Error! Hours cannot be negative or exceed 150" << endl;
cin >> nohours;
if(nohours < 0 || nohours > 150) {
// Nothing to do
}
else {
break;
}
}
}
答案 1 :(得分:0)
我认为作者打算写这样的东西:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int validateHours(int nohours);
int main(int arc, char* argv) {
int nohours;
while (true) {
cin >> nohours;
if (validateHours(nohours) == 0) {
break;
}
}
}
int validateHours(int nohours)
{
if(nohours < 0 || nohours > 150) {
cout << "Error! Hours cannot be negative or exceed 150" << endl;
return -1;
}
return 0;
}