【问题标题】:Recursive function accounting for Negative y values in scheme through a multiply procedure通过乘法过程计算方案中的负 y 值的递归函数
【发布时间】:2018-06-10 17:38:38
【问题描述】:

到目前为止,我只考虑正数和负 x 值。我不确定如何解释负 y 值。这是我所拥有的,

(define (Multiply x y)
(if (= y 0)
0
(+x (Multiply x ( - y 1))
(if (< y 0) //here is where i try to account for negative numbers.
(+ x( - 0 (Multiply x(+ y 1))))))
)
(Multiply 8 3) //outputs 24
(Multiply -9 3) //outputs -27

我需要找到一种方法来解释负 y 值。有点困惑如何做到这一点。 非常新的计划,任何事情都会有所帮助。提前致谢。

【问题讨论】:

  • 我建议只处理递归中的正数,并使用包装器将负输入变为正,然后如果只有一个原始输入为负,则否定结果。
  • 包装器看起来像(define (multiply a b) (let ((p (multiply-unsigned (abs a) (abs b)))) (if (xor (a &lt; 0) (b &lt; 0)) (- p) p)))
  • 在你的例子中,(multiply-unsigned): undefined;
  • 您将定义该函数。我只是想展示如何从乘法中分离出符号。
  • 你是说我应该使用超函数吗?我必须通过一系列加法来实现我的乘法过程。

标签: scheme racket


【解决方案1】:
(define (both-same-sign a b)
  (if (and (> a 0) (> b 0)) #t
  (if (and (< a 0) (< b 0)) #t
  #f)))

(define (make-positive n)
  (if (< n 0) (- n)
  n))

(define (multiply x y)
  (define a (make-positive x))
  (define b (make-positive y))
  (define (multiplier a b)
    (if (or (= a 0) (= b 0)) 0
    (+ a (multiplier a (- b 1)))))
  (define result (multiplier a b))
  (if (both-same-sign x y) result
   (- result)))

【讨论】:

    猜你喜欢
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 2020-06-11
    • 2018-03-07
    • 1970-01-01
    • 2015-07-28
    • 2020-01-29
    相关资源
    最近更新 更多