试图计算总工资
我正在尝试创建一个程序来计算每周员工的总工资。
这是我的代码
(princ"Enter working hours: ")
(defparameter workhours(read))
(if (and (>= workhours 0)) (<= workhours 60))
(princ"Enter hourly pay rate: ")
(defparameter HPrate(read))
(if(<= workhours 40)
(* workhours HPrate))
我很难在 lisp 中构建这个 40*HPrate + (workhours - 40) * HPrate * 1.5
这是公式
(Regular hours/week) Gross Pay = Hours X Rate
(With Overtime) Over Time Pay = ( Hours - 40 ) X Rate X 1.5
Gross Pay = 40 X Rate + Over Time Pay
回答
您应该尝试将代码逻辑与输入/输出操作分开,例如询问数字或写入结果。通常最好只编写给定数字和输出数字的函数。然后,您可以从任何类型的用户界面(图形或文本)调用它。
商业逻辑
您想计算给定工作时间和小时费率的总工资。
因此,您定义了一个名为 的函数,该函数gross-pay将一个数字work-hours和一个作为输入hourly-rate:
(defun gross-pay (work-hours hourly-rate)
10000 ;; a lot of money, just for testing
)
现在已经定义好了,你可以调用它,你的环境会自动打印结果:
* (gross-pay 0 0)
10000
您的代码中的问题之一是您有一个if包含一个测试和三个分支的分支,这不是有效的语法。根据你写的内容,我猜你想要这个逻辑:
(defun gross-pay (work-hours hourly-rate)
(assert (<= 0 work-hours 60))
;; ...
)
的assert检查是否条件成立,否则发出错误信号。我认为在小时数低于零或大于 60 的情况下没有有效的计算,在这种情况下出现错误是有意义的。
然后,你想用你给出的公式计算总工资。
您必须以不同的方式计算正常工作时间、加班时间和两种工作时间的价格(并将它们相加)。
让我们定义一个辅助函数,split-time,它返回两个值,小于或等于 40 的小时数,以及剩余时间(超过 40):
(defun split-time (hours)
(if (> hours 40)
;; the regular amount is maxed to 40
;; overtime is the rest
(values 40 (- hours 40))
;; regular amount is the same as the input
;; no overtime
(values hours 0)))
你可以得到多种的结果values通过multiple-value-bind如下:
(defun gross-pay (work-hours hourly-rate)
(assert (<= 0 work-hours 60))
(multiple-value-bind (regular overtime) (split-time work-hours)
;; here regular and overtime are bound to values
))
最后:
(defun gross-pay (work-hours hourly-rate)
(assert (<= 0 work-hours 60))
(multiple-value-bind (regular overtime) (split-time work-hours)
(+ (* regular hourly-rate)
(* overtime hourly-rate 3/2))))
在这里,我使用3/2而不是1.5因为浮点计算是近似的,但有理数是精确的。例如,结果可以在打印时转换回浮点数。
测试
现在你有了一个函数,你可以测试它:
* (gross-pay 10 1)
10
* (= (gross-pay 50 1)
(+ (* 40 1)
(* 10 3/2)))
T
输入输出
如果需要,您可以将逻辑包装在命令行界面中:
(defun gross-pay/io ()
(gross-pay
(ask "Enter working hours: " '(integer 0 60))
(ask "Enter hourly pay rate: " '(integer 1 1000))))
上面的工作归功于这个辅助函数,它处理请求输入时可能出现的不同问题(清除缓冲、强制输出、读取值时禁用评估、检查类型等)
(defun ask (prompt type)
(let ((*standard-output* *query-io*))
(loop
(clear-input)
(fresh-line)
(princ prompt)
(finish-output)
(let ((value (let ((*read-eval* nil)) (read))))
(if (typep value type)
(return value)
(format *error-output*
"type mismatch: ~a not of type ~a"
value type))))))
在我的环境中,这是一个示例交互:
USER> (gross-pay/io)
Enter working hours: 5
Enter hourly pay rate: 3
15
以及输入错误的示例:
Enter working hours: 87
type mismatch: 87 not of type (INTEGER 0 60)
Enter working hours: ""
type mismatch: not of type (INTEGER 0 60)
Enter working hours: 15
Enter hourly pay rate: 0
type mismatch: 0 not of type (INTEGER 1 1000)
Enter hourly pay rate: 88
1320