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)

Recommended Answers

All 9 Replies

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.

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?

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.

thanks i think i got it without brackets though?

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) ;

Looks good to me. If it gives the right answers, thats OK.

commented: thanks for helping a beginner +1

thanks again for the assistance

@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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.