简体   繁体   中英

Recursion using for-loop

I am currently writing a program in which I have to calculate a number recursively using a for-loop. 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 (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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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