0

我在康奈尔大学课程中使用下面的代码求平方根,但是代码返回错误的值,代码是

fun squareRoot(x: real): real =
  let
    val delta = 0.0001
    fun goodEnough(guess: real): bool =
      if(abs(guess*guess - x) < delta) then true else false
    fun improve(guess: real): real =
      (guess + x/guess) / 2.0
    fun tryGuess(guess: real): real =
      if goodEnough(guess) then guess
      else tryGuess(improve(guess))
  in
    tryGuess(1.0)
  end

执行时

 use "squareroot1.sml";
[opening squareroot1.sml]
val squareRoot = fn : real -> real
val it = () : unit
- squareroot 9.0;
val it = 1.0 : real
-

它总是返回 1.0 作为根,你能告诉为什么会这样吗?

4

1 回答 1

0

调用函数时出现拼写错误,需要squarerootsquareRoot.

于 2013-11-07T03:18:33.353 回答