首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在方案中计算给定数字的数字?递归和迭代。

如何在方案中计算给定数字的数字?递归和迭代。
EN

Stack Overflow用户
提问于 2012-10-04 21:02:43
回答 2查看 1.7K关注 0票数 1

我知道如何计算一个数字的数字之和:

代码语言:javascript
复制
(define (sum-of-digits x)  
  (if (= x 0) 0
      (+ (modulo x 10) 
         (sum-of-digits (/ (- x (modulo x 10))
                           10)))))`

但我只是不知道如何计算数字。也不知道如何通过线性迭代过程来实现。

谢谢!!

EN

回答 2

Stack Overflow用户

发布于 2012-10-04 21:13:46

你离答案很近。

为了弄清楚如何将数字之和转换为数字计数,请尝试编写一些测试用例。测试用例必须包括调用函数的示例以及预期的结果。

顺便提一句,这是一个生成递归的例子,你不应该处理它,直到你做了一系列的问题,比如“在列表中添加数字”,“在列表中计算元素”等等。

票数 0
EN

Stack Overflow用户

发布于 2012-10-04 22:40:01

关于你的每一个问题的提示:

  1. 对于计数数字,不需要添加当前数字(就像代码中的情况一样)。只需添加1
  2. 有几种策略可以将递归解决方案(如您的解决方案)转换为尾递归(生成线性迭代过程的策略)。下面是一个简短的列表:

代码语言:javascript
复制
- Add an extra parameter to the function to hold the result accumulated so far
- Pass the initial value for the accumulator the first time you call the procedure, typically this is the same value that you'd have returned at the base case in a "normal" (non-tail-recursive) recursion.
- Return the accumulator at the base case of the recursion
- At the recursive step, update the accumulated result with a new value and pass it to the recursive call
- And the most important: when the time comes to call the recursion, make sure to call it as the last expression with no "additional work" to be performed.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12735885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档