我想让程序通过add和shift方法将两个数相乘。我已经在sbcl lisp中编写了这段代码。
(defun calculator (num1 num2)
(write-line "In the function")
(let ((res 0))
(loop for lpr from 0 to 63
do (let ((end-bit (logand num2 1)))
(format t "res is : ~a. ~%" num2)
(if (= end-bit 1)
(+ res num1))
(ash num2 -1)
(ash num1 1)
(format t "after ash ~a ~%"num2)))
(format t "result is ~a.~%" res)))
(let ((num1 (progn
(write-line "Enter first number: ")
(finish-output)
(read)))
(num2 (progn
(write-line "Enter second number: ")
(finish-output)
(read))))
(if (or (= num1 0) (= num2 0))
(write-line "result is 0.0")
(calculator num1 num2)))
但res,num2,num1,end-bit变量的值在整个程序中保持不变。我认为逻辑和按位操作没有发生。问题是什么。
答案 0 :(得分:5)
所有函数+
或ash
都没有就地,这意味着你必须将结果设置回变量。
所以你想要更新一个var,就这样做:
(setf num2 (ash num2 -1))
对于增量和减量,有一个名为incf
的就地变体:
(incf res num1) ; (setf res (+ res num1))