为什么前置和后置增量运算符在递归中不起作用?

问题描述 投票:0回答:1

我有以下内容:

public static void main(String[] args){
        Screen.clear();
        System.out.println(depth(5,0));
        
    }

public static int depth(int n, int depth){
        System.out.println(depth);
        if(n == 0)return depth;
        else{
           System.out.println(depth);          
           return depth(n-1, depth++);
        }
        
    }

为什么这总是打印出 0, n 次?为什么深度没有增加?

java recursion post-increment pre-increment
1个回答
-1
投票

你没有预先递增。您的函数在递增之前传递 0,因此实际上不会递增。试试这个:

public static void main(String[] args){
        Screen.clear();
        System.out.println(depth(5,0));
        
    }

public static int depth(int n, int depth){
        System.out.println(depth);
        if(n == 0)return depth;
        else{
           System.out.println(depth);          
           return depth(n-1, ++depth);
        }
    }

或者(如果你想使用后增量)

public static void main(String[] args){
        Screen.clear();
        System.out.println(depth(5,0));
        
    }

public static int depth(int n, int depth){
        System.out.println(depth);
        if(n == 0)return depth;
        else{
           System.out.println(depth++);          
           return depth(n-1, depth);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.