tchristofferson tchristofferson - 5 months ago 19
iOS Question

Why is my GPA Double value not working correctly in Swift?

why isn't this code working when I addA for the first time it works but then it goes to 2.66 and keeps going down from there when it should stay at 4.0.

import UIKit

//Quantity of A A- B+ B B- C+ C C- D+ D D- F
var gradesQuantity = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
var gradesAdded = 0.0
var gpa = 0.0

func addGrades(grades: [Double]) -> Double {
for grade in grades {
gradesAdded += grade
if gradesQuantity[0] <= 0 {
gradesQuantity[0] = 0
}
}

return gradesAdded
}

func calcGPA(grades: [Double]) -> Double {
gpa = (grades[0] * 4.0 + grades[1] * 3.7 + grades[2] * 3.3 + grades[3] * 3.0 + grades[4] * 2.7 + grades[5] * 2.3 + grades[6] * 2.0 + grades[7] * 1.7 + grades[8] * 1.3 + grades[9] * 1.0 + grades[10] * 0.7) / gradesAdded

return gpa
}

class ViewController: UIViewController {

@IBOutlet weak var GPALabel: UILabel!
@IBOutlet weak var GPANumber: UILabel!
@IBOutlet weak var AQuantity: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func AddA() {
gradesQuantity[0] += 1.0
addGrades(gradesQuantity)
let x = calcGPA(gradesQuantity)
GPANumber.text = String(x)
AQuantity.text = String(Int(gradesQuantity[0]))
}

@IBAction func SubtractA() {
gradesQuantity[0] -= 1.0
addGrades(gradesQuantity)
let x = calcGPA(gradesQuantity)
GPANumber.text = String(x)
AQuantity.text = String(Int(gradesQuantity[0]))
}
}


can somebody please help i put this in playground and add code under it that is the same in the buttons and it works but in the project it doesnt work. This leads me to believe the problem is in the addA and subtractA buttons.

Answer

I think the root cause of your problem is that you are doing too much work. If you delete the addGrades function (which isn't really adding any functionality as far as I can tell) and replace your AddA and SubtractA functions with the following, then it will work as intended:

@IBAction func AddA() {
    gradesQuantity[0] += 1.0
    gradesAdded += 1.0
    GPANumber.text = String(calcGPA(gradesQuantity))
    AQuantity.text = String(Int(gradesQuantity[0]))
}

@IBAction func SubtractA() {
    gradesQuantity[0] -= 1.0
    gradesAdded -= 1.0
    GPANumber.text = String(calcGPA(gradesQuantity))
    AQuantity.text = String(Int(gradesQuantity[0]))
}

For further development, I would recommend creating a subclass array that has functions to add and subtract grades and return the GPA. This should make things much more readable and reusable.