为什么当我第一次添加 A 时这段代码不起作用,但后来它变为 2.66 并从那里继续下降,而它应该保持在 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]))
}
}
有人可以帮我把它放在 Playground 上,并在它下面添加与按钮相同的代码,它可以工作,但在项目中它不起作用。这让我相信问题出在 addA 和 subtractA 按钮上。
最佳答案
您正在编写具有副作用的函数(修改外部变量)。尽量避免这种情况。另外,您可能希望程序中有更多的结构。将 gradesQuantity
的位置值与字母等级相关联是可以的,但您可以使用字典做得更好:
enum GradeLetter: Double {
case A = 4.0
case AMinus = 3.7
case BPlus = 3.3
case B = 3
case BMinus = 2.7
case CPlus = 2.3
case C = 2
case CMinus = 1.7
case DPlus = 1.3
case D = 1
case DMinus = 0.7
case F = 0
}
func calculateGPA(grades: [GradeLetter: Int]) -> Double {
let courseCount = grades.reduce(0.0) { aggregate, grade in
return aggregate + Double(grade.1)
}
let totalPoint = grades.reduce(0.0) { aggregate, grade in
return aggregate + grade.0.rawValue * Double(grade.1)
}
return totalPoint / courseCount
}
假设您有 1 个 A
、2 个 A-
和 3 个 B
:
var grades = [GradeLetter: Int]()
grades[.A] = 1
grades[.AMinus] = 2
grades[.B] = 3
print(calculateGPA(grades))
关于ios - 为什么我的 GPA Double 值在 Swift 中不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37893332/