我无法通过此代码输出平均工资率,有人可以解释原因吗?

时间:2016-01-19 16:30:22

标签: c++ logic

为什么此代码无法输出平均工资率?是因为我使用PAYRATE作为常量吗?我试着乱搞那些没有运气的parens。

#include <iostream>

using namespace std;

const double PAYRATE = 20.00;

int main()
{
    double hoursWorked;
    double avgPayRate;

    cout << "Please Enter Hours Worked: " << endl;
    cin  >> hoursWorked;
    cout << endl;

    if (hoursWorked < 40)
    {
        avgPayRate = (hoursWorked * PAYRATE) / hoursWorked;
        cout << "Your Average Pay Rate is: " << avgPayRate << endl;

    }
    else
    {
        avgPayRate = (hoursWorked * PAYRATE) + (1.5 * PAYRATE)
                      * (hoursWorked - 40) / hoursWorked;
        cout << "Your Average Pay Rate is: " << avgPayRate << endl;
    }

    system("pause");
    return 0;
}

2 个答案:

答案 0 :(得分:1)

当工作小时数超过40时,我认为你的公式应该是:

select agg.userid, a_and_b.description, agg.recordid, agg.rec_count
from 
(
  select left(userid,1) as userid, recordid, count(*) as rec_count
  from app
  group by left(userid,1), recordid
) agg
join
(
  select 'A' as userid, recordid, description from a
  union all
  select 'B' as userid, recordid, description from b
) a_and_b on a_and_b.userid = agg.userid and a_and_b.recordid = agg.recordid;

因为您的名义PAYRATE工作时间为40小时,其余时间工作率提高50%。

答案 1 :(得分:0)

请改为尝试:

if (hoursWorked < 40) {
    avgPayRate = PAYRATE;
}
else {
    avgPayRate = ((PAYRATE * 40) + (hoursWorked - 40) * PAYRATE * 1.5) / hoursWorked;
}

cout << "Your Average Pay Rate is: " << avgPayRate << endl;

hoursWorked < 40时无需进行所有计算。

将重复值放在一个地方也是一个好习惯(如果它们发生变化,你只需要编辑一个,这样就不会出错):

int main()
{
    double hoursWorked;
    double avgPayRate;
    const double PAYRATE = 20.00;
    const double normalHours = 40.0;
    const double factor = 1.5;

    cout << "Please Enter Hours Worked: ";
    cin  >> hoursWorked;
    cout << endl;

    if (hoursWorked < normalHours) {
        avgPayRate = PAYRATE;
    }
    else {
        avgPayRate = ((PAYRATE * normalHours)
                     + (hoursWorked - normalHours) * PAYRATE * factor) / hoursWorked;
    }

    cout << "Your Average Pay Rate is: " << avgPayRate << endl;

    system("pause");
    return 0;
}