简体   繁体   中英

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

I am trying to create a function in Playground using Swift where a calculation is made several times, and then added to the total sum of calculations until the loop is over. Everything seems to be working, except that when I try to sum the every calculation to the last total, it just gives me the value of the calculation. Here is my code:

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
}

Am I doing something wrong?

Currently your variable result is scoped to the loop and does not exist outside of it. Additionally every run of the loop creates a new result variable, initialized with 0 .

What you have to do is move the line var result: Float = 0 in front of the for loop:

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
}

Additionally you can remove the repeated assignment of finalResult = result and just do it once after the loop is over.

You can probably remove the finalResult completely. Just write

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM