如何从 Swift 中的无限数中得出一个值?

How to derive a value from a infinite number in Swift?

我下面的函数偶尔会产生无穷大的数字。我原以为我可以使用下面的舍入函数来避免使用无限数...换句话说 1.333333333333(INF) 四舍五入到 1.33,但是编译器仍然将 INF.rounded 的结果视为无限,怎么可能我四舍五入,这样我还能在这里出一个值?具体来说,我正在尝试编码为 JSON 并收到此错误:

metadata ERROR = invalidValue(inf, Swift.EncodingError.Context(codingPath: [Watch_Extension.HockeyTrackerMetadata.(CodingKeys in _B2A7010AF20490DAF638D1E0A01E4982).maximumCapableSpeed], debugDescription: "Unable to encode Double.infinity directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded.", underlyingError: nil))

//Calculation  
 func calculateMaximumAndAverageSkatingEfficiency() {

        let heartRateUnit:HKUnit = HKUnit(from: "count/min")
        let heartRatesAsDouble = heartRateValues.map { [=11=].quantity.doubleValue(for: heartRateUnit)}
        let maxHeartRate = heartRatesAsDouble.max()
        guard let maxHeartRateUnwrapped = maxHeartRate else { return }

        maximumEfficiencyFactor = ((1760.0 * (maxSpeed / 60)) / maxHeartRateUnwrapped).round(to: 2)

        guard let averageIceTimeHeartRateUnwrapped = averageIceTimeHeartRate else { return }

        averageEfficiencyFactor = ((1760.0 * (averageSpeed / 60)) / averageIceTimeHeartRateUnwrapped).round(to: 2)

    }

//Round extension I am using
extension Double {

    func round(to places: Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return Darwin.round(self * divisor) / divisor
    }

}

//Usage 
  if let averageEfficiencyFactorUnwrapped = averageEfficiencyFactor {
            metadata.averageEfficiencyFactor = averageEfficiencyFactorUnwrapped.round(to: 2)
        }

"Infinite value" 表示该值是正无穷大或负无穷大,可能是因为它是除以零或类似数学运算的结果。这并不意味着该值是 non-terminating 小数。

确保 maxHeartRateUnwrappedaverageIceTimeHeartRateUnwrapped 不为零。