我一直收到错误:type mismatch: found Uint required Double
当我在println
方法中放置sqrt
函数时。虽然我很欣赏它的部分Scala防止副作用,但是如何在函数中打印值以便我能理解我的程序?是否有一种“干净”的方法在需要显式返回类型的函数中打印值(如递归函数sqrt)?
代码在这里:
object Newton {
def threshold(guess: Double, x: Double) : Boolean =
if (Math.abs(guess * guess -x) < (0.01/100 * x)) true else false
def improve(guess: Double, x: Double) : Double =
(guess + x/guess) / 2.0
def sqrt(guess: Double, x: Double,
threshold: (Double, Double) => Boolean,
improve: (Double, Double) => Double ): Double =
println("current guess:", guess)
if(threshold(guess,x))
return guess
else
return sqrt(improve(guess, x), x, threshold, improve)
def main(args: Array[String]): Unit = {
println("Sqrt of Two:", sqrt(1,1.0e-20,threshold, improve))
}
}
答案 0 :(得分:2)
你缺少大括号。
def sqrt(guess: Double, x: Double,
threshold: (Double, Double) => Boolean,
improve: (Double, Double) => Double ): Double = { // Add curly braces
println("current guess:", guess)
if(threshold(guess,x))
return guess
else
return sqrt(improve(guess, x), x, threshold, improve)
} // Add curly braces