Do While 和 While 循环在 C++ 代码中不起作用

Do While and While Loops not working in C++ code

你好我正在编写一个 C++ 代码,要求用户输入他们正在使用的互联网服务提供商包,然后代码使用该信息计算他们的每月账单。但是以下代码不起作用。

{
int choice;     
double hours;       

cout << "Which Subscription package have you purchased? 1, 2, or 3? " << endl;
cin >> choice;

switch (choice)
{
case 1:
    cout << "How many hours were used this month? " << endl;        //Package A
    cin >> hours;
        do{     
                cout << "Please enter a valid number of hours used. " << endl;
                cin >> hours;
            } while (hours < 0 || hours > 744);

        double monthlyBill; //Calculated as base price + additional hours

        if (hours >= 11 || hours <= 744)
            monthlyBill = 9.95 + (hours * 2.00);
        else
            monthlyBill = 9.95;

        cout << "Your monthly bill is : $";
        cout << monthlyBill << endl;
        break;

case 2:         //Package B
    cout << "How many hours were used this month?" << endl;
    cin >> hours; 
    while (hours < 0 || hours > 744);       //Input validation
    {
        cout << "Please enter a valid number of hours used. " << endl;
        cin >> hours;
    }

    double monthlyBill_b;   //Calculated as base price + additional hours

    if (hours >= 21 || hours <= 744)
        monthlyBill_b = 14.95 + (hours * 1.00);
    else
        monthlyBill_b = 14.95;

    cout << "Your monthly bill is: $ ";
    cout <<  monthlyBill_b << endl;
    break;

case 3:         //Package C is a flat rate of .95 per month
    cout << "Your monthly bill is .95";
    break;
default: cout << "You did not enter 1, 2, or 3. ";
    break;
}
}

当运行时,代码显示如下:

Which Subscription package have you purchased? 1, 2, or 3?

1

How many hours were used this month?

14

Please enter a valid number of hours used.

如果有人能提供一些关于为什么这不起作用的见解,那将非常有帮助。

提前致谢

do{     
    cout << "Please enter a valid number of hours used. " << endl;
    cin >> hours;
} while (hours < 0 || hours > 744);

应重写为:

while (hours < 0 || hours > 744) {     
    cout << "Please enter a valid number of hours used. " << endl;
    cin >> hours;
}

在前一种情况下,您无条件地输入 while,然后提示消息并(无条件)读取新值。

正确的做法是只有当输入超出范围时才进入循环。

你应该做的:

while (hours < 0 || hours > 744) {
    cout << "Please enter a valid number of hours used." << endl;
    cin >> hours;
} 

这是因为在执行 do-while 循环之前,您已经请求了几个小时 (cin >> hours;)。在这种情况下,您需要一个 while 循环在您 cin >> 小时后立即进行检查。 do-while 循环将执行其块中的所有内容,然后再检查是否必须再次执行该代码块。