【问题标题】:How to fix this code, logical problem I guess如何修复此代码,我猜是逻辑问题
【发布时间】:2019-06-11 13:29:01
【问题描述】:

我在大学,一年级编程,到目前为止一切顺利,然后我坚持这个练习,我必须做一个函数:

function(n1 n2) = n1 * n2 

但不使用 * 运算符。

我们可以使用的是前面两个数字相加的函数。

;Takes two numbers as input and return the sum between them

;Number Number -> Number

;(sum 2 3) = 5

     (define (sum n1 n2)
        (cond
            [(zero? n1) n2]
            [(positive? n1) (sum (sub1 n1) (add1 n2))]
      ))

不要使用 + 或 * 的诀窍是我们必须使用递归函数。

这就是我所做的,这个函数必须返回两个数字的乘积,所以我们知道乘法 3 * 2 是 3 + 3 或 2 + 2 + 2,所以这就是我在这里尝试做的但我想不出来更多

;Takes two numbers as input and return the multiplication between them

;Number Number -> Number

;(mult 3 2) = 6

      (define (mult n1 n2)
         (cond
             [(zero? n1) n2]
             [(positive? n1) (mult (sub1 n1) (sum n1 n2))]
        ))

(mult 3 2) 的输出是 8,这显然不是我需要做的。


解决了!

     (define (mult n1 n2)
         (cond
             [(or (zero? n1) (zero? n2)) 0] ;verify if zero is one of the inputs and return it
             [(eq? 1 n1) n2] ;if n1 is one return n2
             [(eq? 1 n2) n1] ;if n2 is one return n1
             [(positive? n1) (sum n2 (mult (sub1 n1) n2))] ;if it none of the adove, add n2 n1Times to itself
      ))

谢谢! @Barmar @coredump

【问题讨论】:

  • 你确定[(zero? n1) n2]?你认为(mult 0 2) 的结果是 2 吗?
  • 哈哈我现在觉得很愚蠢,因为没看到
  • 不过,这是一个很好的教训。当递归函数的行为不符合预期时,首先要检查的事情之一是基本案例是否真的有意义。
  • 你的递归步骤也不对。(mult 4 5)(mult 3 6)不一样。
  • 替代方案是(mult 4 5) == (sum 5 (mult 3 5)) == (sum 5 (sum 5 (mult 2 5))) ...

标签: recursion scheme lisp racket


【解决方案1】:

提示:这里是带有参数 5 和 3 的预期递归函数的执行轨迹,其中每个嵌套级别对应于 MULT 的递归调用:

  0: (MULT 5 3)
    1: (MULT 4 3)
      2: (MULT 3 3)
        3: (MULT 2 3)
          4: (MULT 1 3)
            5: (MULT 0 3)
            5: MULT returned 0
          4: MULT returned 3
        3: MULT returned 6
      2: MULT returned 9
    1: MULT returned 12
  0: MULT returned 15

请注意,这里的递归深度是 5,但你可以聪明一点,让它改为 3。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-25
    • 2020-10-31
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    相关资源
    最近更新 更多