数学值无法正确计算

时间:2014-02-18 21:41:11

标签: java math system.out

出于某种原因,我得到的数学价值不同于我应有的数学价值。我在这里做错了什么?

代码:

overtimeHours = hoursWorked - 40;

regularPay = hourlyWage * hoursWorked - overtimeHours;
overtimePay = 1.5 * hourlyWage * overtimeHours;
totalPay = hourlyWage * hoursWorked + overtimePay;

输出:

Please enter employee's name: John
Please enter The Dragon's hourly wage: 22.50
Please enter how many hours The Dragon worked: 48.5

John's Wages
Regular Pay: $    1082.75
Overtime Pay: $    286.88
Total Pay: $    1378.13

1 个答案:

答案 0 :(得分:9)

操作顺序,就像你在基础数学中学到的一样。你正在计算

(hourlyWage * hoursWorked) - overtimeHours

相反,你想要

hourlyWage * (hoursWorked - overtimeHours)

此外,您不应该在total中重新计算;相反,只需添加常规和加班。

最后,正如@CodeMonkey所说,你无条件地假设这个人正在加班。以下是我的建议:

if(hoursWorked > 40) {
    regularHours = 40;
    overtimeHours = regularHours - 40;
} else {
    regularHours = hoursWorked;
    overtimeHours = 0;
}