我正在尝试在Swift中使用递归来打印斐波那契数列以进行n次迭代。但是,我一直收到相同的错误。
我已经尝试过不递归地做到这一点,并且能够做到。但是,我现在正在尝试通过使用递归以更复杂和“计算机科学”的方式进行操作。
func fibonacciSequence (n: Int) -> [Int] {
// Consumes a number "n", which is the number of iterations to go through with the Fibonacci formula and prints such sequence.
var fibonacciArray = [Int]()
for n in 0 ... n {
if n == 0 {
fibonacciArray.append(0)
}
else if n == 1 {
fibonacciArray.append(1)
}
else {
fibonacciArray.append (fibonacciSequence(n: (n - 1)) +
fibonacciSequence(n: (n-2)))
}
}
return fibonacciArray
我希望用数字n调用该函数,并让该函数打印出斐波那契数列。示例:如果n = 5,我希望控制台输出0、1、1、2、3、5。我得到的错误是:(无法将类型[Int]的值转换为预期的参数类型Int )。
答案 0 :(得分:0)
如上所述,返回值相加时会导致错误。修复代码的一种可能的方法(但不是递归的)是简单地更改else
语句:
func fibonacciSequence (n: Int) -> [Int] {
// Consumes a number "n", which is the number of iterations to go through with the Fibonacci formula and prints such sequence.
var fibonacciArray = [Int]()
for n in 0 ... n {
if n == 0 {
fibonacciArray.append(0)
}
else if n == 1 {
fibonacciArray.append(1)
}
else {
fibonacciArray.append (fibonacciArray[n-1] + fibonacciArray[n-2] )
}
}
return fibonacciArray
}
递归解决方案如下:
func fibonacciSequence (n: Int, sumOne: Int, sumTwo: Int, counter: Int, start: Bool) {
if start {
print(0)
print(1)
}
if counter == -1 {
print(1)
}
if (counter == n - 2) {
return
}
let sum = sumOne + sumTwo
print(sum)
fibonacciSequence(n: n, sumOne: sumTwo , sumTwo: sum, counter: counter + 1, start: false)
}
fibonacciSequence(n: 8, sumOne: 0, sumTwo: 1, counter: 0, start: true)
可能有一种“更精细”的方法,但我希望它能有所帮助。干杯。
答案 1 :(得分:0)
这是我在 swift 5 playground 中对 fabonacci 系列的解决方案
func fibonacci(n: Int) {
var num1 = 0
var num2 = 1
var nextNum = Int()
let i = 1
var array = [Int]()
array.append(num1)
array.append(num2)
for _ in i...n {
nextNum = num1 + num2
num1 = num2
num2 = nextNum
array.append(num2)
print(array)
}
print("result = \(num2)")
}
打印(斐波那契(n:5))
答案 2 :(得分:0)
let fibonacci = sequence(state: (0, 1)) {(state: inout (Int, Int)) -> Int? in
defer { state = (state.1, state.0 + state.1) }
return state.0
}
//limit 10
for number in fibonacci.prefix(10) {
print(number)
}
答案 3 :(得分:-1)
fabonacci的递归方式->解决方案
func fibo( n: Int) -> Int {
guard n > 1 else { return n }
return fibo(n: n-1) + fibo(n: n-2)
}