简体   繁体   中英

Stuck SICP Exercise 1.1.7 in Javascript

I've decided to try working through the MIT SICP course, but in Javascript.

The following code outputs undefined, but it should output a fairly accurate guess of the square root of 5.

I've tested all of the smaller functions and they all work as expected, the problem must be somewhere in the recursive guessRoot() function, but I can't seem to see the problem.

var square = function(x) {
    return x * x;
};
var abs = function(x) {
    return x > 0 ? x : -x;
};
var goodEnough = function(g, x) {
    return abs(square(g) - x) < 0.01;
};
var average = function(x, y) {
    return (x + y) / 2;
};
var improve = function(g, x) {
    return average(g, (x / g));
};
var guessRoot = function(guess, x) {
    if (goodEnough(guess, x)) {
        return guess;
    } else {
        guessRoot(improve(guess, x), x);
    }
};
console.log(guessRoot(2.5, 5));

Looks like you're just missing a return in the recursive step.

var guessRoot = function(guess, x) {
    if (goodEnough(guess, x)) {
        return guess;
    } else {
        return guessRoot(improve(guess, x), x); // ... here
    }
};

http://jsfiddle.net/mattball/TyLsL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM