简体   繁体   English

递归函数数字总和 R

[英]Recursive function sum of digits R

I try to write a recursive function that returns the sum of digits.我尝试编写一个返回数字总和的递归函数。 However, the program below doesn't seem to do the trick.然而,下面的程序似乎并没有做到这一点。

getSum = function(i) {
    if (i < 0) {Print("Please enter a positive number")}
    if (i >= 0) {getSum(i - floor(i / 10) - i %% 10) + floor(i / 10) + i %% 10}

It gives two errors:它给出了两个错误:

Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
Error during wrapup: evaluation nested too deeply: infinite recursion / 
options(expressions=)?

What can I do to solve this?我能做些什么来解决这个问题?

Use this用这个

if (i >= 0)
{sum(sapply(strsplit(as.character(i),""),as.numeric))}

Of course this works for whole numbers.当然,这适用于整数。 If your need is greater more regex can be added to accommodate that如果您的需求更大,可以添加更多正则表达式来适应

Edited!已编辑! Oops totally missed that you want a recursive function哎呀完全错过了你想要一个递归函数

Do you want something like this?你想要这样的东西吗?

getSum = function(i){
    i = abs(floor(i))
    if (nchar(i) == 1){
        return(i)
    } else {
        getSum(floor(i/10)) +i%%10 #Minorpt (suggested by @DashingQuark)
    }
}

In R, it is recommended to use Recall for creating a recursive function.在 R 中,建议使用Recall来创建递归函数。

I am using @db's function, but demonstrating with Recall我正在使用@db 的函数,但使用Recall演示

getSum = function( i ) 
{
  if (nchar(i) == 1){
    return(i)
  } else if (i < 0 ) {
    "Please enter a positive number"
  }else {
    print(i)
    Recall( i = floor(i/10)) +i%%10 
  }
}

getSum(0)
# [1] 0
getSum(1)
# [1] 1
getSum(-1)
# [1] "Please enter a positive number"
getSum(5)
# [1] 5
getSum(100)
# [1] 100
# [1] 10
# [1] 1
getSum( 23)
# [1] 23
# [1] 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM