理解递归中的负数 [英] Understanding negative numbers in recursion

查看:81
本文介绍了理解递归中的负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是使用 Eloquent Javascript 一书来了解 javascript 中的递归,但不完全理解这个小提琴中的负数 (-1) 发生了什么:

I'm just getting my head around recursion in javascript using the book Eloquent Javascript but don't fully understand what is happening to the negative number (-1) in this fiddle:

http://jsfiddle.net/greenhulk01/kg5ton1t/

function isEven(n) {
    if (n == 0) {
        return true;
    } else if (n == 1) {
        return false;
    } else if (n < 0) {

        return isEven(-n);
    } else {
        return isEven(n - 2);
    }
};

console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → false

我理解这个递归中发生的一切,除了return isEven(-n);"正在处理.使用 console.log 我可以看到它返回为 undefined 所以不确定为什么它被错误语句捕获.

I understand everything that is going on in this recursion except for how "return isEven(-n);" is being handled. Using console.log i can see it is returned as undefined so not sure why it is caught by the false statement.

任何有助于我理解的指针将不胜感激.

Any pointers to help my understanding would be really appreciated.

干杯.

推荐答案

isEven(-n) 只是利用了这样一个事实:如果 -n 是偶数,n 也是偶数.所以基本上 isEven(-10) 调用 isEven(10)

isEven(-n) just takes advantage of the fact that if -n is even, n is even, too. So basically isEven(-10) calls isEven(10)

顺便说一句:你试过 isEven(1.5) 吗?我希望是假的,但我猜你会得到堆栈溢出.我会把它写成

BTW: Did you try isEven(1.5)? I'd expect false, but I'd guess you'd get a stack overflow. I'd write this as

function isEven(n) {
  if (n < 0) {
    return isEven(-n);
  }
  if (n >= 2) {
    return isEven(n - 2);
  }
  return n == 0;
}; 

顺便说一句 2:不使用递归,你可以只写

BTW 2: Without using recursion, you could just write

function isEven(n) {
  return n % 2 == 0;
}

这篇关于理解递归中的负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆