[英]Unable to see console output in assistant editor using swift playground
[英]No output in Swift Playground
我試圖將斐波那契數放在數組中,並想在運動場控制台中查看數組輸出,但是由於某些原因,我看不到任何輸出。 有人可以幫助我理解我在程序中犯的錯誤嗎?
import UIKit
class FibonacciSequence {
let includesZero: Bool
let values: [Int]
init(maxNumber: Int, includesZero: Bool) {
self.includesZero = includesZero
values = [0]
var counter: Int
if (includesZero == true) { counter = 0 }
else { counter = 1 }
for counter <= maxNumber; {
if ( counter == 0 ) {
values.append(0)
counter = 1
}
else {
counter = counter + counter
values.append(counter)
}
}
println(values)
}
println(values)
return values
}
let fibanocciSequence = FibonacciSequence(maxNumber:123, includesZero: true)
@ABakerSmith已按原樣為您很好地解決了代碼中的問題,但是您可能還想考慮,而不是使用一個初始化數組成員變量的類,而是編寫一個返回斐波那契數字的SequenceType
:
struct FibonacciSequence: SequenceType {
let maxNumber: Int
let includesZero: Bool
func generate() -> GeneratorOf<Int> {
var (i, j) = includesZero ? (0,1) : (1,1)
return GeneratorOf {
(i, j) = (j, i+j)
return (i < self.maxNumber) ? i : nil
}
}
}
let seq = FibonacciSequence(maxNumber: 20, includesZero: false)
// no arrays were harmed in the generation of this for loop
for num in seq {
println(num)
}
// if you want it in array form:
let array = Array(seq)
如果要提高多代性能,您當然可以記住該順序。
您的問題是您的代碼中有錯誤。 如果您的代碼中有錯誤,Playgrounds將不會運行它,並且您將不會獲得任何輸出。
在for counter <= maxNumber;
的行上for counter <= maxNumber;
您有分號,但是,我很確定您不能聲明這樣的for
循環,除非我遺漏了什么? 您可以使用while
循環。
為什么要嘗試從init
方法返回values
?
您已將values
聲明為常量,但隨后嘗試使用append
對其進行更改。
使用此代碼並修復所陳述的錯誤不會產生斐波那契數列,而是會產生: [0, 0, 2, 4, 8, 16, 32, 64, 128]
試試這個代碼:
class FibonacciSequence {
let values: [Int]
init(maxNumber: Int, includesZero: Bool) {
var tempValues = includesZero ? [0] : [1]
var current = 1
do {
tempValues.append(current)
let nMinus2 = tempValues[tempValues.count - 2]
let nMinus1 = tempValues[tempValues.count - 1]
current = nMinus2 + nMinus1
} while current <= maxNumber
self.values = tempValues
}
}
然后創建一個實例:
let fibanocciSequence = FibonacciSequence(maxNumber:123, includesZero: true)
println(fibanocciSequence.values) // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.