简体   繁体   English

递归 function 指数 function

[英]Recursive function exponential function

I need implement recursive function exponential function (e^x) with help row Taylor: e^x = 1 + x + x2/2.我需要在帮助行 Taylor 的帮助下实现递归 function 指数 function (e^x):e^x = 1 + x + x2/2。 + x3/3. + x3/3。 +.:. +.:. But i can't understand what i do wrong I have next code:但我不明白我做错了什么我有下一个代码:

function fact(n){
    return n * fact(n - 1);
}

function myPow(x, n){
    return x * myPow(x, n - 1);
}

function expon(x ,n){
    if(n == 1){
        return expon(x, n - 1) * x;
    }
    else{
        return expon(x, n - 1) + (myPow(x, n)/fact(n));
    }

}

console.log(expon(1, 10));

Your factorial function has no base case. 您的阶乘函数没有基本情况。

function fact(n) {
  if (n == 1)
    return 1;
  if (n < 1)
    return 0;
  return n * fact(n - 1);
}

A similar change will be needed for myPow . myPow将需要类似的更改。 Although since powers are funny, I think if n == 0 return 1. 尽管由于幂是有趣的,但我认为如果n == 0则返回1。

Your code should look like this: 您的代码应如下所示:

function fact(n){
  if (n == 1)
    return 1;
  return n * fact(n - 1);
}

function myPow(x, n){
  if(n == 1)
    return n;
  return x * myPow(x, n - 1);
}

function expon(x ,n){
  if(n == 1){
    return 1;
  }
  else{
    return expon(x, n - 1) + (myPow(x, n)/fact(n));
  }

console.log(expon(1, 10));

This looks like an assignment so I won't debug your code but give you some hints. 这看起来像一个作业,所以我不会调试您的代码,但会给您一些提示。

You seem to not understand how recursion ends with giving a result in the end. 您似乎不明白递归到底是如何结束的。

You have to provide a simple case where you return a value with a non recursive call. 您必须提供一种简单的情况,其中您使用非递归调用返回值。

Sometimes you don't write any if (bad!), and sometimes there is an if , but both cases use a recursive call. 有时您不编写任何if (不好!),有时又有一个if ,但是两种情况都使用递归调用。

This will solve your problem:这将解决您的问题:

function fact(n) {
  if (n == 1) return 1;
  return n * fact(n - 1);
}

function myPow(x, n) {
  if (n == 0) return 1;
  return x * myPow(x, n - 1);
}

function expon(x, n) {
  if (n == 0) return 1;
  return expon(x, n - 1) + myPow(x, n) / fact(n);
}
console.log(expon(1, 10));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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