swift - 如何从 Int 的 sqrt 得到最近的 Int floored?

标签 swift

我需要等于或小于 n 的 sqrt 的最大 int。

我收到无法在不可变值上使用可变成员:“sqrt”返回不可变值

func isPrime (n:Int) ->  Bool {
    if n < 2 { return false }

    generatePrimes(to: sqrt(Double(n)).round(.towardZero))

.squareRoot同样的问题

如何在此处生成 to:Int?

最佳答案

FloatingPoint 中有两种不同的方法协议(protocol):

mutating func round(_ rule: FloatingPointRoundingRule)
func rounded(_ rule: FloatingPointRoundingRule) -> Self

第一个改变接收者,第二个返回一个新值。你想使用第二个:

sqrt(Double(n)).rounded(.towardZero)

Double(n).squareRoot().rounded(.towardZero)

但是如果您需要整数形式的结果,那么它就是

Int(Double(n).squareRoot())

因为从 DoubleInt 的转换已经截断 结果趋向于零。

关于swift - 如何从 Int 的 sqrt 得到最近的 Int floored?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51115967/

相关文章:

swift - Swift 中有没有一种方法可以计算 3 个数字的所有可能加法、乘法、减法或除法。包括括号

ios - 如何使用泛型 `Results` 声明可选类属性

json - 如何将 String 数组转换为 Swiftyjson JSON 类型

swift - Swift 中的 super.init() 递归问题

ios - 如何在 swift 4 中隐藏 SexyTooltip?

ios - 更改拉动刷新事件指示器

ios - 设置导航 Controller 上方和 popupView 下方的 View

ios - PDFKit 交换注释内容

swift - 从静态表格 View 单元格条件转场(快速)

ios - 如何在没有 Storyboard的情况下调整 iPad 和 iPhone 4S 的 View 大小?