2015-12-20 88 views
0

我想在Playground中使用Swift創建一個函數,在其中進行多次計算,然後將其添加到計算總和中,直到循環結束。一切似乎都在起作用,除了當我試圖將每次計算總結到最後總計時,它只是給了我計算的價值。這裏是我的代碼:Swift-'For'循環不向總結果添加變量

func Calc(diff: String, hsh: String, sperunit: Float, rate: Float, n: Int16, p: Float, length: Int16) -> Float { 
    //Divisions per Year 
    let a: Int16 = length/n 
    let rem = length - (a*n) 
    let spl = Calc(diff, hsh: hash, sperunit: sperunit, rate: rate) 

    for var i = 0; i < Int(a) ; i++ { //also tried for i in i..<a 
     var result: Float = 0 
     let h = (spl * Float(n)/pow (p,Float(i))) //This gives me a correct result 
     result += h //This gives me the same result from h 

     finalResult = result 
    } 
    finalResult = finalResult + (Float(rem) * spl/pow (p,Float(a))) //This line is meant to get the result variable out of the loop and do an extra calculation outside of the loop 
    print(finalResult) 
    return finalResult 
} 

我做錯了什麼?

回答

2

當前變量result的作用域爲循環範圍,並且不在其外部。此外,循環的每次運行都會創建一個新的result變量,並使用0進行初始化。

你必須做的是招行var result: Float = 0for循環的面前:

var result: Float = 0 
for var i = 0; i < Int(a) ; i++ { 
    let h = (spl * Float(n)/pow (p,Float(i))) 
    result += h 

    finalResult = result 
} 

此外,您可以刪除的finalResult = result重複分配,只是做一次後循環結束。您可以完全刪除finalResult。只需編寫

var result: Float = 0 
for var i = 0; i < Int(a) ; i++ { 
    let h = (spl * Float(n)/pow (p,Float(i))) 
    result += h 
} 
result += (Float(rem) * spl/pow (p,Float(a))) 
print(result) 
return result 
+0

完美解決!非常感謝!! –

+0

@JacoboKoenig歡迎您隨時充分利用您最新獲得的有用答案:) – luk2302