0

hello everyone. i have been attempting to make an if statement that calculates overtime hours for quite some time now and i cant seem to get it to work correctly. Is it possible to make this statement with 1 line? or am i missing somthing? this is what i thought would work, but apparently it doesnt... :(

if (hours<=40)
    pay = rate * hours;
if (hours>40)
    pay= (hours - 40 * 1.5 * rate) + (rate*hours)

Edited by JamesCherrill: Zombie thread

3
Contributors
9
Replies
21
Views
7 Years
Discussion Span
Last Post by cmackbrown
0

You can simplify this by using "else" rather than 2 "if" tests

if (hours<=40)   pay = rate * hours;
  else  pay= (hours - 40 * 1.5 * rate) + (rate*hours);

or compress it all into 1 line with the "?" operator

pay = (hours<=40) ? rate * hours : (hours - 40 * 1.5 * rate) + (rate*hours);

In either case you need to look again at (hours - 40 * 1.5 * rate) remembering that the * operator has precidence over the - operator. Even after that, if the correct overtime is 1.5x, you are paying twice for the overtime in your formula.

Finally, you could compress this down to 1 line without any explicit conditional test by using man & max, but that would obscure the meaning of the code, and IMHO would be a bad thing.

Edited by JamesCherrill: n/a

0

well lets see...

if (hours<=40)
pay = rate*hours;

else 
pay = (40*rate) + ((1.5*rate)*(hours-40));

does that look like it would work out?

Edited by shroomiin: n/a

0

That's better, but still got a problem with (1.5*rate+hours-40)

What you want to do is:
subtract 40 from hours
multiply result by 1.5*rate
You'll need brackets to get the calculation done in the right order.

Anyway - feed in some test data for which you know what the answer should be, and see how it goes.

0

thanks i think i got it without brackets though?

Edited by shroomiin: n/a

0

either way, here is what i came up with. and it does work with my tested data...do you see a problem with it?

if (hours <=40)
			pay = rate*hours;
			
			if (hours > 40)
			pay = (1.5 * rate) * (hours-40) + (rate*40) ;
0

@euji. Please check out the Daniweb member rules before posting...

DaniWeb Member Rules include:
"Do not hijack old threads by posting a new question as a reply to an old one"
"Do provide evidence of having done some work yourself if posting questions from school or work assignments"
http://www.daniweb.com/community/rules
Please start your own new thread for your question

This thread is closed.

0

DaniWeb Member Rules include:
"Do not hijack old threads by posting a new question as a reply to an old one"

Please start your own new thread for your question

This thread is closed

Edited by JamesCherrill: Please start your own new thread for your question