0

以下代码有什么问题:

咖啡脚本:

sqrt = (n) -> 
    small = 0.01
    lo = 0
    hi = (n+1)/2
    while hi > lo
        mid = (lo+hi)/2
        diff = Math.pow(mid, 2) - n
        sign = (diff > 0) ? 1 : 0
        if Math.abs(diff) < small
            return mid
        else
            switch sign
                when 1
                    hi = mid
                when 0
                    lo = mid
console.log (sqrt 33)

Javascript:

// Generated by CoffeeScript 1.3.3
(function() {
  var sqrt;

  sqrt = function(n) {
    var diff, hi, lo, mid, sign, small, _ref;
    small = 0.01;
    lo = 0;
    hi = (n + 1) / 2;
    debugger;
    while (hi > lo) {
      mid = (lo + hi) / 2;
      diff = Math.pow(mid, 2) - n;
      sign = (_ref = diff > 0) != null ? _ref : {
        1: 0
      };
      if (Math.abs(diff) < small) {
        return mid;
      } else {
        switch (sign) {
          case 1:
            hi = mid;
            break;
          case 0:
            lo = mid;
        }
      }
    }
  };

  console.log(sqrt(33));

}).call(this);

另一件事是当您处于无限循环或递归调用中时,您甚至无法打开控制台。浏览器只是冻结。这太烦人了。任何人都可以阐明这一点吗?

4

2 回答 2

2

这部分:

sign = (diff > 0) ? 1 : 0

应该:

sign = if (diff > 0) then 1 else 0

?是为存在运算符保留的。

另请参阅:文档

于 2012-10-10T09:07:11.943 回答
0

根据您的咖啡脚本代码

sign = (_ref = diff > 0) != null ? _ref : {
    1: 0
};

应该看起来像

sign = (diff > 0) ? 1 : 0;
于 2012-10-10T09:05:52.410 回答