【问题标题】:How to divide UnitMass in Swift?如何在 Swift 中划分 UnitMass?
【发布时间】:2019-09-02 14:12:39
【问题描述】:

我正在尝试构建一个简单的应用程序,允许用户输入他们的体重,输入他们的目标体重,并输入他们计划每周减掉多少。

我希望它回复说,例如(你重 12 石和 2 磅,你想重 10 石和 0 磅,如果你每周减掉 2 磅,你将在 15 周内达到目标)。

(请注意,我对 Swift 很陌生,我更习惯于 Python。我希望创建一个基于预设方程的计算器。

我尝试从整数和双精度值开始,然后在最后转换为 UnitMass,但没有成功

import UIKit
import Foundation

// enter your current weight
var myCurrentWeight = Measurement(value:12, unit: UnitMass.stones)

//enter your goal weight
var myGoalWeight = Measurement(value:10, unit: UnitMass.stones)

//enter how much you plan to lose a week
var weightLoss = Measurement(value:2, unit: UnitMass.pounds)

// find the difference inbetween the weights (Example: 12st - 10st = 2st)
let weightDifference = myCurrentWeight - myGoalWeight

//find out how many weightLoss's fit into the difference, this
let numOfWeeks = weightDifference / weightLoss

// print the number of weeks it takes to reach your goal
print(numOfWeeks)

预计打印:28 我得到的错误是:“二元运算符'/'不能应用于两个'测量'操作数”

【问题讨论】:

  • 您的编辑只是取消了对格式的修复。请在发布前修复您的格式。努力让人们更容易为您提供帮助。
  • 删除了编辑。感谢您的反馈。
  • 您希望用石头值除以磅值,然后以某种方式得到周数。 weightLoss 需要以“每周磅”为单位,才能计算出数学和单位。但是Measurement API 不直接支持两个Measurement 实例的乘法或除法。

标签: swift user-input units-of-measurement


【解决方案1】:

您可以使用 Measurement 类型在值之间进行转换,如下所示:

import Foundation

// this is a Double
var myCurrentWeight = 12.0

// this is a Double
var myGoalWeight = 10.0

// Convert Double value `2` as pounds to Double value as stones
var weightLoss = Measurement(value:2, unit: UnitMass.pounds).converted(to: UnitMass.stones).value

// find the difference inbetween the weights (Example: 12st - 10st = 2st)
let weightDifference = myCurrentWeight - myGoalWeight

//find out how many weightLoss's fit into the difference, this
let numOfWeeks = weightDifference / weightLoss

// print the number of weeks it takes to reach your goal
print(numOfWeeks)

这定义了一个值和它的单位:Measurement(value:2, unit: UnitMass.pounds)。然后您可以将其转换为另一个单位 .converted(to: UnitMass.stones)

使用Measurement 转换不同单位的值,并能够用它们进行计算。

在您的Measurement 实例上使用.value 来获得它的Double 表示,用它来计算。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 2017-05-11
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多