Swift- 'For' 循环不向总结果添加变量

Swift- 'For' Loop not adding variable to total result

我正在尝试使用 Swift 在 Playground 中创建一个函数,其中进行多次计算,然后添加到计算的总和中,直到循环结束。一切似乎都在工作,除了当我尝试将每个计算加到最后一个总数时,它只是给了我计算的值。这是我的代码:

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
}

我是不是做错了什么?

目前您的变量 result 在循环范围内,不存在于循环之外。此外,循环的每个 运行 都会创建一个新的 result 变量,用 0.

初始化

你要做的是将 var result: Float = 0 行移到 for 循环前面:

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