简体   繁体   English

使用for循环递归

[英]Recursion using for-loop

I am currently writing a program in which I have to calculate a number recursively using a for-loop.我目前正在编写一个程序,在该程序中我必须使用 for 循环递归计算一个数字。 But unfortunately, I have no idea how to correctly implement this function since my current implementation does not calculate the correct answers.但不幸的是,我不知道如何正确实现这个函数,因为我当前的实现没有计算出正确的答案。

public class Calc {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        double k = sc.nextDouble();
        double e = sc.nextDouble();
        double q = sc.nextDouble();
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            k = (k + (i * e)) * (1 + q);  //The problem I have is that I don't know how to access the previous element of the for-loop
        }   

    }
}

Instead of your for loop:而不是你的 for 循环:

for (int i = 0; i < n; i++) {
    k = (k + (i * e)) * (1 + q);
}

You can indeed use recursion.你确实可以使用递归。

Just make a method called calculateK() and call it recursively, like so:只需创建一个名为calculateK()的方法并递归调用它,如下所示:

public static double calculateK(double k, int i) {
    if (i == n) {
        return k;
    }
    else 
    {
        return calculateK((k + (i * e)) * (1 + q), i + 1);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM