我正在制作一個 BMI 應用程式。我有這個代碼:
enum MathHelper {
static func computeBMI(kg: Decimal, cm: Decimal) -> Decimal {
return kg / cm / cm * 10_000
}
static func computeWeight(cm: Decimal, bmi: Decimal) -> Decimal {
return bmi * cm * cm / 10_000
}
static func computeWeightRange(
cm: Decimal,
bmiRange: (from: Decimal, to: Decimal))
-> (from: Decimal, to: Decimal)
{
let fromWeight = computeWeight(cm: cm, bmi: bmiRange.from)
let toWeight = computeWeight(cm: cm, bmi: bmiRange.to)
return (from: fromWeight, to: toWeight)
}
}
現在我列印從/到對,長度為 1。
print(Decimal.FormatStyle.number.precision(.fractionLength(1)).format(from))
print(Decimal.FormatStyle.number.precision(.fractionLength(1)).format(to))
當我以身高 180 厘米運行這段代碼時,BMI 范圍從 18.5 到 24.9(這是健康體重的 BMI 范圍),我得到了 59.9 - 80.7 的體重范圍。
但這是不正確的。體重范圍應為59.7-80.8。因為如果我將 59.7 和 80.8 放入computeBMI函式并以 1 小數長度列印結果,它仍然在 18.5-24.9 范圍內。
隨意嘗試一下。這是最小的可重現代碼:
enum MathHelper {
static func computeBMI(kg: Decimal, cm: Decimal) -> Decimal {
return kg / cm / cm * 10_000
}
static func computeWeight(cm: Decimal, bmi: Decimal) -> Decimal {
return bmi * cm * cm / 10_000
}
static func computeWeightRange(
cm: Decimal,
bmiRange: (from: Decimal, to: Decimal))
-> (from: Decimal, to: Decimal)
{
let fromWeight = computeWeight(cm: cm, bmi: bmiRange.from)
let toWeight = computeWeight(cm: cm, bmi: bmiRange.to)
return (from: fromWeight, to: toWeight)
}
}
func format(_ decimal: Decimal) -> String {
return Decimal.FormatStyle.number.precision(.fractionLength(1)).format(decimal)
}
let height: Decimal = 180
let upperBMI: Decimal = 24.9
let computedUpperWeight = format(MathHelper.computeWeight(cm: height, bmi: upperBMI))
// this prints out 80.7, which is incorrect, because 80.8 is the correct answer (see below)
print("computed upper weight: \(computedUpperWeight)")
let correctUpperWeight: Decimal = 80.8
let bmiFromCorrectUpperWeight = format(MathHelper.computeBMI(kg: correctUpperWeight, cm: height))
// This prints out 24.9, which is still within the uppoer bound
print("BMI from correct upper weight \(bmiFromCorrectUpperWeight)")
uj5u.com熱心網友回復:
雖然 flanker 的論點是有效的,但 BMI 值在實際應用中通常以 1 精度表示。
我的建議是將您的 BMI 圖表范圍調整 0.05。
例如,使用這兩個范圍(我參考維基百科)。
- 正常:18.5-24.9
- 超重 25-29.9
您可以像這樣在代碼中表示您的范圍:
- 正常:18.45-24.95
- 增持 24.95-29.95
這應該可以解決您的問題。
uj5u.com熱心網友回復:
問題在于您顯示的值的準確性,而不是計算。在四舍五入中丟失了 80.7 和 80.8 公斤之間的 BMI 差異。
180cm 的 BMI 上限為 80.676 kg,然后四舍五入 do 1dp 為 80.7 kg。
以另一種方式計算體重 80.8 公斤的 180 厘米的 BMI 提供 24.938 的 BMI ......在這種準確度下,這顯然大于健康 BMI 范圍的上限 24.9,但是當向下舍入到1 dp由于舍入損失了精度,它似乎在范圍內。
這里的數學是正確的。問題在于您如何在 UI 中表示它,以便用戶理解這些內容。這是一個表示邏輯的問題,而不是數學問題,這與所問的問題不同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/447588.html
上一篇:KotlinMultiplatform在iOS上使用NSUserDefaultssetValueString出錯
