gpt4 book ai didi

swift - 如何在 Swift 中划分 UnitMass?

转载 作者:搜寻专家 更新时间:2023-11-01 06:53:16 25 4
gpt4 key购买 nike

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

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

(请注意,我是 Swift 的新手,我更习惯使用 Python。我希望创建一个基于预设方程式的计算器)。

我试过从 Integers 和 Doubles 的值开始,然后在最后转换为 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我得到的错误是:“二元运算符‘/’不能应用于两个‘测量’操作数”

最佳答案

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

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 表示,用它来计算。

关于swift - 如何在 Swift 中划分 UnitMass?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55641010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com