gpt4 book ai didi

java - 尝试弄清楚递归基础知识

转载 作者:行者123 更新时间:2023-12-01 11:56:20 24 4
gpt4 key购买 nike

如果有人能向我解释我编写的这段代码与我想象的结果相差甚远,我真的会很高兴。我编写了代码试图证明 int n 将是 n = 4 所以在我的头脑和纸上我认为我一步步的结果将是随后:

  1. 4 * 4 + (3) = 19

  2. 3 * 3 + (2) = 11

  3. 2 * 2 + (1) = 5

  4. 1 * 1 + (0) = 1

  5. 返回0

    有人能告诉我为什么不是这样吗?并引导我完成递归步骤?

    public static void main(String[] args) {

    Scanner kbd = new Scanner(System.in);

    int n;
    System.out.println("Enter a number: ");
    n = kbd.nextInt();

    System.out.println("recursive value "+intValue(n));
    }
    public static int intValue(int n)
    {
    int total;
    int x;
    if(n == 0)
    return 0;
    else
    total = n * n + intValue(n-1);
    System.out.println("Recursive total: "+total);
    return total;
    }

最佳答案

以下是递归步骤,从 n4 开始:

intValue(4)
n is not 0. total is 4 * 4 + intValue(3)
intValue(3)
n is not 0. total is 3 * 3 + intValue(2)
intValue(2)
n is not 0. total is 2 * 2 + intValue(1)
intValue(1)
n is not 0. total is 1 * 1 + intValue(0)
intValue(0)
n is 0, intValue(0) returns 0.
1 * 1 + 0 = 1.
Print Recursive value: 1, intValue(1) returns 1.
2 * 2 + 1 = 5.
Print Recursive value: 5, intValue(2) returns 5.
3 * 3 + 5 = 14.
Print Recursive value: 14, intValue(3) returns 14.
4 * 4 + 14 = 30.
Print Recursive value: 30, intValue(4) returns 30.

回到main,初始调用返回30,并打印递归值30

递归调用不会返回要添加的n - 1本身;它返回以 n - 1 作为参数再次调用 intValue 的结果。

关于java - 尝试弄清楚递归基础知识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28420868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com