我想计算每轮跑动次数并显示在跑动率标签上。
如您在我的代码中所见,运行速率将随着我使用步进器进行运行和运行而发生变化。
运行速率需要显示到小数点后 2 位(例如 4.50 或 10.74 等)
我想创建函数,但我不知道如何计算。
我该怎么做?
// RUNS
var runsInt = 0
var oversFloat: Float = 0.0
var runRate: Double = 0.0
@IBOutlet weak var runsLabel: UILabel!
@IBOutlet weak var displayRunsLabel: UILabel!
@IBOutlet weak var oversLabel: UILabel!
@IBOutlet weak var oversRectangle: UILabel!
@IBOutlet weak var displayOversLabel: UILabel!
@IBOutlet weak var runRateLabel: UILabel!
@IBOutlet weak var displayRunRateLabel: UILabel!
@IBAction func RunStepper(_ sender: UIStepper) {
let runsValue = Int(sender.value)
displayRunsLabel.text = String(runsValue)
}
// OVERS
@IBAction func OversStepper(_ sender: UIStepper) {
let value = Int(sender.value)
let remainder = value % 10
if remainder == 6 {
sender.value = Double(value + 4)
} else if remainder == 9 {
sender.value = Double(value - 4)
}
displayOversLabel.text = String(format: "%.1f", sender.value / 10)
}
最佳答案
我用了this page有关计算运行率的信息。
runRate = (total runs scored)/(total overs faced)
注意:如果 overs
为 47.5
,则步进值将为 475.0
并且
oversInt
将设置为 475
。计算runRate
时,47.5
实际上代表 47 5/6
我们可以计算为
双(oversInt/10) + Double(oversInt % 10)/6
创建一个名为 calculateRunRate
的函数并
将属性观察器(didSet
)添加到runsInt
和oversInt
以触发runRate
的计算。然后,只要这些值中的任何一个发生变化,runRate
都会重新计算,displayRunRate
标签也会更新。
// RUNS
var runsInt = 0 {
didSet {
calculateRunRate()
}
}
@IBOutlet weak var runsLabel: UILabel!
@IBOutlet weak var displayRunsLabel: UILabel!
@IBAction func RunStepper(_ sender: UIStepper) {
runsInt = Int(sender.value)
displayRunsLabel.text = String(runsInt)
}
// OVERS
var oversInt = 0 {
didSet {
calculateRunRate()
}
}
@IBOutlet weak var oversLabel: UILabel!
@IBOutlet weak var oversRectangle: UILabel!
@IBOutlet weak var displayOversLabel: UILabel!
@IBAction func OversStepper(_ sender: UIStepper) {
var value = Int(sender.value)
let remainder = value % 10
if remainder == 6 {
value += 4
} else if remainder == 9 {
value -= 4
}
sender.value = Double(value)
oversInt = value
displayOversLabel.text = String(format: "%.1f", sender.value / 10)
}
// RUN RATE
var runRate = 0.0
let maxOvers = 40.0
@IBOutlet weak var runRateLabel: UILabel!
@IBOutlet weak var displayRunRateLabel: UILabel!
@IBOutlet weak var displayRequiredRunRateLabel: UILabel!
func calculateRunRate() {
var oversDouble = 0.0
// Don't divide by zero
if oversInt == 0 {
// can this even happen?
// set runRate to some value that makes sense
runRate = 0.0
} else {
oversDouble = Double(oversInt / 10) + Double(oversInt % 10) / 6
runRate = Double(runsInt) / oversDouble
}
displayRunRateLabel.text = String(format: "%.2f", runRate)
// required run rate
let targetScore = Int(targetScoreLabel.text ?? "") ?? 0
var requiredRunRate = 0.0
if oversDouble < maxOvers {
requiredRunRate = Double(targetScore - runsInt) / (maxOvers - oversDouble)
}
displayRequiredRunRateLabel.text = String(format: "%.2f", requiredRunRate)
}
关于ios - 计算并显示为标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53878139/