gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:13:02 24 4
gpt4 key购买 nike

我需要等于或小于 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com