Scala 如何求完美平方的平方根?
我正在做这个简单的任务,实现这个函数,试图在Scala中找到一个完美平方的平方根,然后用这个简单的测试方法测试它。我做错了什么Scala 如何求完美平方的平方根?,scala,Scala,我正在做这个简单的任务,实现这个函数,试图在Scala中找到一个完美平方的平方根,然后用这个简单的测试方法测试它。我做错了什么 def squareRootOfPerfectSquare(a: Int): Option[Int] = if (scala.math.sqrt(a) % 1 == 0) scala.math.sqrt(a) else -1 当您将返回类型指定为选项[T]时,应返回Some或None def squareRootOfPerfectSqua
def squareRootOfPerfectSquare(a: Int): Option[Int] =
if (scala.math.sqrt(a) % 1 == 0)
scala.math.sqrt(a)
else
-1
当您将返回类型指定为
选项[T]
时,应返回Some
或None
def squareRootOfPerfectSquare(a: Int): Option[Int] = {
val sqrt = math.sqrt(a)
if (sqrt % 1 == 0)
Some(sqrt.toInt)
else
None
}
我想说的是,最好的方法是留在Int世界中,以避免双精度的任何舍入和精度问题
def squareRootOfPerfectSquare(a: Int): Option[Int] = {
int sqrt = (int) Math.round(math.sqrt(a));
if (sqrt * sqrt == a)
Some(sqrt)
else
None
}
首先,您将函数的结果类型声明为
Option[Int]
,但尝试从中返回Double
(scala.math.sqrt(a)
),我对scala还是新手。我不知道选项[Int]是做什么的…我的函数已经有了选项[Int],我想实现。。。有没有正确实施的想法?请阅读以下示例: