java中递归函数返回问题

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

16 11 6 1 -4 1 6 11 16 我做了这个递归函数,但我认为 return 语句导致了问题

16 - 5 = 11 11 - 5 = 6 。 。 1 - 5 = -4 //数字达到负数。 5×5,直到我们回到起点。 -4 + 5 = 1 1 + 5 = 6 。 。 11 + 5 = 16

public static void main(String args[]) {
    
    Scanner input = new Scanner(System.in);
    int a = input.nextInt();
    int tempA = a;
    boolean durum = true;

    dondur(a, tempA, durum);

}

public static void dondur(int a, int tempA, boolean durum) {

    if (a >= -5 && durum == true) {
        System.out.println(a);
        dondur(a - 5, tempA, durum);
    }
    if (a < 0) {
        a = a + 10;
    }

    if (a <= tempA) {
        durum = false;
        System.out.println(a);
        dondur(a + 5, tempA, durum);
    }

    if (a > tempA) {
        return;
    }

}

预计:16 11 6 1 -4 1 6 11 16

我的输出:16 11 6 1 -4 1 6 11 16 6 11 16 1 6 11 16 6 11 16 11 16 16

java recursion methods return
1个回答
0
投票

递归序列问题

您使用递归函数和布尔标志来控制方向的想法很好,但是您的代码中存在一些问题。这些问题导致输出不符合预期。

我对代码的更改:

  1. 添加了基本情况,其中 a 变得大于
    tempA
    ,而
    durum
    为 false。
  2. 调整了打印冗余值的多个 if 语句。每个 if 子句都会单独检查。
  3. 您可以在函数内部更改
    durum
    ,但是
    Java
    按值传递原始类型变量,并且它不会在函数调用之间持续存在。解决此问题的方法是翻转
    durum
    并显式传递错误值。

固定代码:

import java.util.Scanner;

public class RecursiveSequence {
    
    // Main Class
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        int a = input.nextInt();
        int tempA = a;
        boolean durum = true;
        dondur(a, tempA, durum);
    }
    
    // Static void method with parameters
    public static void dondur(int a, int tempA, boolean durum) {
    
        // Prints the current value of the variable a
        System.out.println(a);

        // Checks if variable durum is true or not
        if (durum == true) {
            if (a > -5) {
                dondur(a - 5, tempA, durum);
            } else {
                // Flip the direction
                dondur(a + 5, tempA, false);
            }
        }
       else {
            // Checks for the base case
            if (a < tempA) {
                dondur(a + 5, tempA, durum);
            }
        }
    }
}

如有任何疑问,请随时询问!

© www.soinside.com 2019 - 2024. All rights reserved.