我需要等于或低于 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 在这里?
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已经
将结果截断为零。
| 归档时间: |
|
| 查看次数: |
309 次 |
| 最近记录: |