简体   繁体   English

如何在Java中运行递归函数

[英]how to run recursive function in Java

I am trying to learn Dynamic Programming and one of the examples they give in Wikipedia of what is not Dynamic Programming, is a recursive way of getting Fibonacci sequence up to certain number. 我正在尝试学习动态编程,并且他们在Wikipedia中提供了非动态编程的示例之一,这是一种将斐波那契序列提高到一定数量的递归方法。 IE IE浏览器

Given a recursive function, say: 给定一个递归函数,说:

fib(n) = 0 if n = 0
         1 if n = 1
         fib(n - 1) + fib(n - 2) if n >= 2

We can easily write this recursively from its mathematic form as: 我们可以很容易地从其数学形式中将其写为:

function fib(n)
  if(n == 0 || n == 1)
    n
  else
    fib(n-1) + fib(n-2)

But I cannot get the pseudo code to work. 但是我无法使伪代码正常工作。

when I do this method in Java, I get an error the operator + is undefined for methods void : 当我在Java中执行此方法时,出现错误,未定义operator +的方法void

 public void fib(int n) {

     if (n == 0 || n == 1) {

         System.out.println(n);
     } else
         return fib(n - 1) + fib(n - 2);

 }

in the line with return fib(n - 1) + fib(n - 2) , you add the return values of the fib() function. 在带有return fib(n - 1) + fib(n - 2) ,添加fib()函数的返回值。 So you should actually return a (int) value, even if n==0||n==1. 因此,即使n == 0 || n == 1,您实际上应该返回一个(int)值。

 public int fib(int n) {

     if (n == 0 || n == 1) {
         return n;
     }
     else {
         return fib(n - 1) + fib(n - 2);
     }
 }

you then call and print you result from outside the function: 然后调用并打印函数外部的结果:

System.out.println(fib(42));

It has no return type so you can't mathematically add it to anything, let alone itself. 它没有返回类型,因此您不能在数学上将其添加到任何内容中,更不用说本身了。

public void fib(int n)  //returning void

Give it a return type 给它一个返回类型

public int fib(int n) //yey \o/

Try this. 尝试这个。

public class Test
{
public static int fib( int n )
{
    if ( n == 0 || n == 1 )
        return n;
    else
        return fib( n - 1 ) + fib( n - 2 );
}

public static void main( String[] args )
{
    System.out.println(fib( 6 ));
}
}

Just change return type of fib function to int. 只需将fib函数的返回类型更改为int即可。 and in function change 以及功能变更

if (n == 0 || n == 1){return n; }

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

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