首页 新闻 会员 周边

为什么return不出来啊?????

0
悬赏园豆:20 [已解决问题] 解决于 2015-12-07 22:24

var L = 0.001;
var V;
function f(x){
  return x*(x+2);
}

function goldenSection(a,b,x1,x2){
  var y1 = f(x1),
  y2 = f(x2);
  if (Math.abs(b - a) < L) {
    V = (y1 < y2)? x1 : x2;
    // console.log(V);
    return V;
  }else if (y1 > y2) {
    goldenSection(x1, b, x2, x1+0.618*(b-x1));
  }else if (y1 <= y2) {
    goldenSection(a, x2, a+0.382*(x2-a), x1);
  }
}

var a = -3,
b = 5,
x1 = a + 0.382 * (b-a),
x2 = a + 0.618 * (b-a),
x = goldenSection(a,b,x1,x2),
y = f(x);
console.log(V); // 这里能输出
console.log(x); // 但是这里为什么输出不了啊。

 为什么输出不了,这个设计JS中的什么知识点。跪求大神指点。晕了。

js
大贱豪的主页 大贱豪 | 初学一级 | 园豆:127
提问于:2015-12-07 22:15
< >
分享
最佳答案
0

已解决,也是就是else 中没有返回。

改成如下解决。

var L = 0.001;
function f(x){
return x*(x+2);
}

function goldenSection(a,b,x1,x2){
var y1 = f(x1),
y2 = f(x2),
value;
if (Math.abs(b - a) < L) {
value = (y1 < y2)? x1 : x2;
return value;
}else if (y1 > y2) {
value = goldenSection(x1, b, x2, x1+0.618*(b-x1));
}else if (y1 <= y2) {
value = goldenSection(a, x2, a+0.382*(x2-a), x1);
}
return value;
}

var a = -3,
b = 5,
x1 = a + 0.382 * (b-a),
x2 = a + 0.618 * (b-a),
x = goldenSection(a,b,x1,x2),
y = f(x);
console.log(x);

大贱豪 | 初学一级 |园豆:127 | 2015-12-07 22:23
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册