Need help with salary calculator!

When someone works 41 hours or more. They get paid 1.5x more so my problem is that in my else if statement. I did rate * 1.5 which should translate into 10 * 1.5 = 15 but I get 425 because my code on the top probably, but I don't understand it at the moment.
He gave us this example. Which I'm trying to emulate.
"
Enter hours worked (-1 to end): 41
Enter hourly rate of the employee ($00.00): 10.00
Salary is $415.00
"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

int main()
{ 
	double salary=1,rate=0,hours=0,counter=0;
	cout << "Enter your hours worked: ";
	cin >> hours;
	cout << "Enter your rate: ";
	cin >> rate;
	
	while(counter<=hours)
	{	salary=hours*rate;
		counter++;
	}
		if(hours==-1)
			{exit(0);
		}
		else if(hours>=41)
		{
		rate = rate * 1.5;
		salary = salary + rate;
		}
		
	cout << salary;

	return 0;
}

Last edited on
You should just look at the problem in terms of base pay + overtime.
base pay is hours up to 40 * rate..
overtime is hours over 40 * rate * 1.5.

get overtime hours by subtracting 40 from the total hours, and only add overtime if the difference is greater than 0.
There are a couple of ways to solve this problem but first I think you should make sure what your instructor wants.

Does he mean if you work more than 40 hours you get paid 1.5 times the rate on all 41 hours, or just on hours worked past 40 hours.

Ie if an employee worked 45 hours, they would get paid (40 * 1.0 * $10/hr) + (5 * 1.5 * $10/hr)

or does he want an employee who worked 45 hours to get compensated (45 * 1.5 * $10/hr) vs an employee who worked 39 hours to get compensated (39 * 1.0 * $10/hr)


The way your loops are set up are bad though, your rate gets changed on every loop were hours is greater than 40. You should probably only change the rate once, if at all.

You could do a simple while loop like this (assuming your instructor wants different compensation rates for hours below 40 and above 40)

maybe

1
2
3
4
5
6
while(counter <= hours)
{
     salary = salary + rate; //adds one hours worth of wage to salary for each iteration
     if (counter > 40) {salary = salary + rate/2.0;} //add's the bonus wage for hours worked over 40 if the iteration is above.
     counter++;
}


you'd probably want to change your initializations to
double salary=0,rate=0,hours=0,counter=1

Last edited on
Topic archived. No new replies allowed.