Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 如何求完美平方的平方根?_Scala - Fatal编程技术网

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

我正在做这个简单的任务,实现这个函数,试图在Scala中找到一个完美平方的平方根,然后用这个简单的测试方法测试它。我做错了什么

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],我想实现。。。有没有正确实施的想法?请阅读以下示例: