如何从 Int 的 sqrt 获得最近的 Int?

rob*_*más 1 swift

我需要等于或低于 n 的 sqrt 的最大整数。

我得到无法在不可变值上使用变异成员:'sqrt'返回不可变值

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

    generatePrimes(to: sqrt(Double(n)).round(.towardZero))
Run Code Online (Sandbox Code Playgroud)

同样的问题 .squareRoot

我如何生成 to:Int 在这里?

Mar*_*n R 5

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

mutating func round(_ rule: FloatingPointRoundingRule)
func rounded(_ rule: FloatingPointRoundingRule) -> Self
Run Code Online (Sandbox Code Playgroud)

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

sqrt(Double(n)).rounded(.towardZero)
Run Code Online (Sandbox Code Playgroud)

或者

Double(n).squareRoot().rounded(.towardZero)
Run Code Online (Sandbox Code Playgroud)

但是,如果您需要将结果作为整数,那么它只是

Int(Double(n).squareRoot())
Run Code Online (Sandbox Code Playgroud)

因为从Doubleto的转换Int已经 将结果截断为零。