在C ++中初学“while”程序

时间:2015-02-16 16:35:08

标签: c++

我必须解决一个问题,我计算员工的工资,他们在前40小时内每小时得到10欧元,然后每增加一小时他们得到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;
}

5 个答案:

答案 0 :(得分:5)

while更改为if s。

while内的条件始终为true,因为hours始终小于40,因为在hours条件中没有修改while因此导致无限循环

修改后的代码:

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;
}

答案 1 :(得分:3)

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

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

循环中的某些内容必须以导致hourshours <= 40的方式修改false

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

答案 2 :(得分:2)

你正在使用while循环,就像他们的陈述一样。

使用两个变量,一个用于计算工作小时数,一个用于从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;
}

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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

如果您的代码以无限循环打印,则应始终检查为何不符合终止条件的原因。

在您的情况下,您的循环在hours < 40(第一种情况)和hours > 40(第二种情况)时终止。您不是在循环中修改小时数,因此它会陷入无限循环。