C++初级"while"课程

Beginner "while" program in C++

本文关键字:课程 while C++ 初级      更新时间:2023-10-16

我必须解决一个问题,我计算员工的工资,他们在前 10 小时内每小时获得 40 欧元,然后每隔一小时他们获得 15 欧元。我已经解决了问题,但我的控制台在无限循环中打印答案,我不知道我错在哪里。

int hours;
double salary;
int main()
{
    cout << "Enter amount of hours worked" << endl;
    cin >> hours;
    while (hours <= 40)
    {
        salary = hours * 10;
        cout << "Salary of the employee is: " << salary << endl;
    }
    while (hours > 40)
    {
        salary = (40 * 10) + (hours - 40) * 15;
        cout << "Salary of the employee is: " << salary << endl;
    }
    system("pause");
    return 0;
}

while s 更改为 if s。

while 内部的条件总是true的,因为hours总是小于 40,因为while条件内部的hours没有修改,因此会导致无限循环

修改后的代码:

int hours;
double salary;
int main()
{
    cout << "Enter amount of hours worked" << endl;
    cin >> hours;
    if (hours <= 40)
    {
        salary = hours * 10;
        cout << "Salary of the employee is: " << salary << endl;
    }
    else //I have removed the condition because if hours is not less than 40,
        // it has to be greater than 40!
    {
        salary = (40 * 10) + (hours - 40) * 15;
        cout << "Salary of the employee is: " << salary << endl;
    }
    system("pause");
    return 0;
}

使用 while 循环的解决方案。

由于您一心想获得while循环解决方案,

法典:

int hours;
int counthour = 0;
double salary;
int main()
{
    cout << "Enter amount of hours worked" << endl;
    cin >> hours;
    while (counthour <= hours)
    {
        if(counthour <= 40)
            salary += 10;
        else
            salary += 15;
        counthour++;
    }
    cout << "Salary of the employee is: " << salary << endl;
    system("pause");
    return 0;
}

为了使以下循环不是无限的

while (hours <= 40)
{
    salary = hours * 10;
    cout << "Salary of the employee is: " << salary << endl;
}

循环中的某些内容将不得不以一种会导致hours <= 40 false的方式修改hours

目前,只有salary在该循环中被修改。

你正在使用 while 循环,就像它们是 if 语句一样。

使用两个变量,一个变量获取工作小时数,另一个变量从 0 开始并计算每个支付的小时数。

int hours;
int hourscounted = 0;
double salary;
int main()
{
    cout << "Enter amount of hours worked" << endl;
    cin >> hours;
    while (hourscounted  <= hours)
    {
        if(hourscounted < 40)
        {
            salary = salary + 10;
        }
        else
        {
            salary = salary + 15;
        }
        hourscounted++;
    }
    cout << "Salary of the employee is: " << salary << endl;
    system("pause");
    return 0;
}

将 while 更改为 if :P 并提示将来 - 不要使用 endl,除非你真的需要这样做。你可以在循环/if语句之外进行打印(cout(。它永远不会结束,while循环,它取决于一些东西,没有改变。

编辑:在更详细地阅读了您的代码和问题之后,似乎您应该用if替换while以满足您正在查看的逻辑。

如果您的代码在无限循环中打印,则应始终检查为什么不满足其终止条件。

在您的情况下,循环在hours < 40(第 1 种情况(和hours > 40(第 2 种情况(时终止。你没有修改循环中的小时数,所以它被困在一个无限循环中。