计算几个小时的现金,到8个小时的现金为3 $,8以后为+5.没有“如果" [英] Calculate cash for hours, cash till 8 hours is 3$, after 8 it goes +5. Without "if"

查看:73
本文介绍了计算几个小时的现金,到8个小时的现金为3 $,8以后为+5.没有“如果"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像标题中所说的那样,我想在Lua上使用一个数学函数来计算: 如果一个人工作8个小时,则每小时可获得3美元的报酬. 8小时后的任何额外小时,他每小时将获得5美元的报酬.

Like the title says, I want a mathematical function on Lua to calculate: If a guy is working 8 hours, he gets paid 3$ per hour. For any extra hour after 8 hours he gets paid 5$ per hour.

仅可用功能为math.abs和math.floor.否,如果使用.这对我来说是一个挑战,但我失败了,以为你可以做到:)

Only functions available are math.abs and math.floor. No if usage. It was a challenge for me and I failed, thought you could do it :)

推荐答案

对于此函数中的所有逻辑,我都使用math.floor(hours/8.1).我这样做的方法是将基于逻辑的数字乘以该魔术数字,该数字将等于0(如果小时数小于8.1)或1(如果小时数为8.1或更大).当然,如果您使用的小时数大于16,这将失败,这时它将开始将加班时间乘以2,但是如果您每天工作16小时,则无论如何您都应该获得双倍的加班时间;)

I used math.floor(hours/8.1) for all of the logic in this function. The way I did it was by multiplying the logic based numbers by this magic number, which will either evaluate to 0 (if the hours are less than 8.1) or 1 (if the hours are 8.1 or greater). Of course, this will fail if you use hours greater than 16, at which point it will start multiplying the overtime by 2, but if you're working a 16 hour day, you probably deserve double overtime anyways ;)

我使用8.1而不是8,因此逻辑不会在8小时的工作日触发,只有在8小时以​​上的工作日才会触发.其余代码相当简单(只是试图避免我过度使用括号)

I used 8.1 instead of 8, that way the logic won't trigger on an 8 hour work day, only on a work day above 8 hours. The rest of the code is fairly straightforward (just try to look past my excessive use of parentheses)

function calculatePay(hours)
  return (3*hours)+((2*math.floor(hours/8.1))*((hours-8)*math.floor(hours/8.1)))
end

print(calculatePay(6)) -- 6*3 is 18 for regular pay, no overtime
print(calculatePay(8)) -- 8*3 is 24 for regular pay, no overtime
print(calculatePay(10)) -- 10*3 is 30 for regular pay, plus 4 (2*2) overtime 
print(calculatePay(12)) -- 12*3 is 36 for regular pay, plus 8 (4*2) overtime

这篇关于计算几个小时的现金,到8个小时的现金为3 $,8以后为+5.没有“如果"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆