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
}
我做錯了什麼?
完美解決!非常感謝!! –
@JacoboKoenig歡迎您隨時充分利用您最新獲得的有用答案:) – luk2302