Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

sequence - Fibonacci function from book "The Book of R"

What modification is needed so function returns a sequence without the number 1 duplicated?

myfib<- function(){
        fib.a<-1
        fib.b<- 1
        cat(fib.a,", ",fib.b,",",sep="")
        repeat{
                temp<- fib.a+fib.b
                fib.a<-fib.b
                fib.b<-temp
                cat(fib.b,", ", sep="")
                if(fib.b>150){
                        cat("BREAK NOW...")
                        break
                }
        }
}

instead of 1, 1, 2, 3, 4, 8, 13, 21, 34, 55, 89, 144, 233, BREAK NOW...

return 1, 2, 3, 4, 8, 13, 21, 34, 55, 89, 144, 233, BREAK NOW...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Remove the first number from your cat:

myfib <- function() {
    fib.a <- 1
    fib.b <- 1
    cat(fib.b, ", ", sep="")
    repeat {
        temp <- fib.a + fib.b
        fib.a <- fib.b
        fib.b <- temp
        cat(fib.b, ", ", sep="")
        if(fib.b > 150) {
            cat("BREAK NOW...")
            break
        }
    }
}

Or change the initial values:

myfib <- function() {
    fib.a <- 1
    fib.b <- 2
    cat(fib.a, ", ", fib.b, ", ", sep="")
    repeat {
        temp <- fib.a + fib.b
        fib.a <- fib.b
        fib.b <- temp
        cat(fib.b, ", ", sep="")
        if(fib.b > 150) {
            cat("BREAK NOW...")
            break
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...