Question

For some reason, I am getting different mathematical values than I should be. What am I doing wrong here?

Code:

overtimeHours = hoursWorked - 40;

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

Output:

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
Was it helpful?

Solution

Order of operations, just like you learned in basic math. You're calculating

(hourlyWage * hoursWorked) - overtimeHours

Instead, you want

hourlyWage * (hoursWorked - overtimeHours)

Additionally, you shouldn't recalculate in your total; instead, just add regular and overtime.

Finally, as @CodeMonkey notes, you're unconditionally assuming that the person is working overtime. Here's what I suggest instead:

if(hoursWorked > 40) {
    regularHours = 40;
    overtimeHours = regularHours - 40;
} else {
    regularHours = hoursWorked;
    overtimeHours = 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top