Scheme中的递归乘法(负数问题) [英] Recursive Multiplication in Scheme (trouble with negatives)

查看:86
本文介绍了Scheme中的递归乘法(负数问题)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用递归在 Scheme 中进行乘法运算,并且我能够使用正数而不是负数(它们陷入无限循环).我认为问题出现在第 3 行和第 4 行,我写这些是为了能够处理底片.任何帮助将不胜感激:)

I am trying to multiply in Scheme using recursion, and I am able to do so with positive numbers but not negatives (they get stuck in an infinite loop). I assume the problem comes in the 3rd and 4th lines, which I wrote in an attempt to be able to handle negatives. Any help would be appreciated :)

(define Multiply(lambda (x y)
                      (if (eq? x 0) 0 (if (eq? y 0) 0 ;if either x or y are zero, return 0
                         (if (> 0 x) (- 0 (+ x (Multiply x (- y 1)))) 
                             (if (> 0 y) (- 0 (+ x (Multiply x (- y 1))))
                                 (+ x (Multiply x (- y 1)))))))))

推荐答案

因为乘法是结合的,你可以有

Since multiplication is associative, you can have

x * (-1 * y)  =  (x * -1) * y

考虑到这一点,当 y 小于零时,您可以将 y 转换为正数,方法是将 xy 与 <代码>-1.考虑以下几点:

With this in mind, you can convert y to positive whenever it is less than zero, by multiplying both x and y with -1. Consider the following:

(define (multiply x y)
  (cond
    ((zero? x) 0)
    ((zero? y) 0)
    ((< y 0)
     (multiply (- x) (- y)))
    (else
     (+ x (multiply x (sub1 y))))))

这篇关于Scheme中的递归乘法(负数问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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