swift - Swift 中的基础数学

标签 swift

我是 Xcode 的新手,正在尝试制作一个计算毛利的简单应用。

我正在尝试使用以下代码,但它返回值“0”。

有什么想法吗?

// Playground - noun: a place where people can play

import UIKit

var costPrice = 10

var salePrice = 100

var grossProfit = ((salePrice - costPrice) / salePrice) * 100

println(grossProfit)

最佳答案

Apple 免费出版的 iBook“Swift 简介”的前几页对此进行了解释。

Swift 是类型安全的,会从上下文推断类型。

var costPrice = 10 推断变量 costPrice 是一个 int。

然后您不能将整数与其他类型的数字(例如 double )隐式组合。

如果你试试这个..

let costPrice = 10.0

let salePrice = 100.0

let grossProfit = ((salePrice - costPrice) / salePrice) * 100.0

你会发现这行得通。

关于swift - Swift 中的基础数学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26890394/

相关文章:

swift - 分解语句而不是使用逗号

ios - 注册后向 PFUser 添加列?解析, swift

ios - 在 Swift 中使用泛型返回不同的约束类型

ios - SwiftUI:ViewModifier 不监听 onReceive 事件

swift - 没有数据通过 NSUserDefaults 传递

ios - 通过 tcp 套接字流式传输 PCM 音频

swift - 不能下标类型为 '[Int16]' 的值

swift - 我该如何修复此错误 - 无法将以下代码中类型 'UIImageView' 的值转换为预期参数类型 'UIImage'

ios - 如何添加背景音乐

swift - 如何以编程方式在 NSDocument macOS 应用程序中打开文档?