我正在尝试构建一个简单的应用程序,允许用户输入他们的体重,输入他们的目标体重,并输入他们计划每周减掉多少。
我希望它返回说,例如(你重 12 石头和 2 磅,你想重 10 石头和 0 磅,如果你每周减掉 2 磅,你将在 15 周内达到你的目标(。
(请注意,我对 Swift 很陌生,我更习惯于 Python。我希望创建一个基于预设方程的计算器(。
我尝试从整数和双精度值开始,然后在最后转换为单位质量,但没有运气
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我得到的错误是:"二元运算符'/'不能应用于两个'测量'操作数">
您可以使用度量类型在值之间进行转换,如下所示:
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
表示形式,请使用它进行计算。