计算斐波那契中递归调用的次数 [英] Count number of recursive calls in fibonacci

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

问题描述

我有斐波那契的递归方法.我正在尝试获取该方法的调用次数.当索引为3、4、5、6等时,计数输出应为3、5、9、15等.我的代码给了我错误的输出.也许我的 for 循环正在影响它?请帮忙!

I have the recursion method of Fibonacci. I am trying to get the number of calls for the method. When the index are 3, 4, 5, 6 and so on, the count output should be 3, 5, 9, 15 and so on. My code is giving me wrong outputs. Maybe my for-loop is affecting it? Please help!

import java.util.*;

public class RecursionCallsFib{
   private static int count;
   public static int rabbit(int n) {  //Fibinocci method 
      count++;
      if (n <= 2) {
         return 1;
      } 
      else  {// n > 2, so n-1 > 0 and n-2 > 0     

         return rabbit(n-1) + rabbit(n-2);
      }  
   }  

   public static void main(String [] args){
    System.out.println("Index" + "\t" + "Value" + "\t" + "Count");
      for(int p=1;p<=15;p++){ 
        System.out.println(p + "\t" + rabbit(p) + "\t" + count);

      }
   }
}

推荐答案

如评论中所建议的,您必须正确初始化和重置count.

As proposed in the comment, you must initialize and reset count properly.

private static int count = 0; // <- initializing

// rabbit is ok

public static void main(String[] args) {
    System.out.println("Index" + "\t" + "Value" + "\t" + "Count");
    for (int p = 1; p <= 15; p++) {
        System.out.println(p + "\t" + rabbit(p) + "\t" + count);
        count = 0; // <- resetting
    }
}

这篇关于计算斐波那契中递归调用的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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