作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我需要等于或小于 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())
因为从 Double
到 Int
的转换已经截断结果趋向于零。
关于swift - 如何从 Int 的 sqrt 得到最近的 Int floored?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51115967/
我是一名优秀的程序员,十分优秀!