有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的递归问题

我试图用Java解决递归问题,但我还是坚持用这个。我要把问题放在这里,把我做过的事情放在一边。谢谢你的帮助:D

一种新型病毒已经被发现,一家公司要求我们编制一个公式,让我们能够了解病毒在某一时间的数量增长情况。最初,在时间0(h)时,我们有32个病毒,每小时病毒数量翻一番。此外,每小时添加固定数量的病毒(num)

a)执行递归函数,计算一小时内给定的病毒总数和给定病毒的固定数量

b)计算0、1和2小时的病毒数量,固定数量为10

这就是我所做的:

public static void main (String [] Args) {
    Scanner in = new Scanner(System.in);
    int h, v, f, result;
    f = 10;
    v = 32;
    System.out.println("Hours: ");
    h = in.nextInt();
   result =  TotalVirus (h, v, f);
    System.out.println("Total : " + result);
}

public static int TotalVirus (int h, int v, int f) {
    int counter = 1, result;

    if ( counter == h) {
        return 1;
    }
    else {
      counter = counter + 1;
      v = v + 32 + f;
      result = TotalVirus(h,v,f);  

    }
    return result;

}

}

我真的不知道在if语句上写什么来结束递归


共 (2) 个答案

  1. # 1 楼答案

    按如下方式操作:

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] Args) {
            Scanner in = new Scanner(System.in);
            int h, v, f, result;
            f = 10;
            v = 32;
            System.out.println("Hours: ");
            h = in.nextInt();
            result = TotalVirus(h, v, f);
            System.out.println("Total : " + result);
        }
    
        public static int TotalVirus(int h, int v, int f) {
            if (h == 0) {
                return v;
            }
            return TotalVirus(h - 1, 2 * v + f, f);
        }
    }
    

    运行示例:

    Hours: 
    0
    Total : 32
    

    另一个示例运行:

    Hours: 
    1
    Total : 74
    

    另一个示例运行:

    Hours: 
    2
    Total : 158
    
  2. # 2 楼答案

    您只需要一个尾部递归函数,如下所示:

    public static int totalVirus (int h, int v, int f) {
    
        if ( h == 0 ) {
          return v;
        } 
        return totalVirus( h-1, 2*v + f, f );
    
    
    }
    

    所以你从一个小时开始,比如说h = 2,然后在每次调用中减少它。在递减时,您添加2*v + f,因为每小时病毒会加倍,并且还会添加固定数量的病毒。 当时间到达0时,您只需返回现有的病毒数量