简体   繁体   中英

StackOverflowError with Recursion

Can anyone tell me why I am getting this error? It is really bugging me. What I am trying to do is find the sum of the expression 2^k +1 as k ranges from 1 through n.

import java.util.*;

public class mySums
{
private static double n;

public static void main(String[] args)
{
    recurSum(4);
    System.out.println();
}

/*  public static void iterativeSum (int num)
{

}
*/
public static double recurSum (double num)
{
    if (n==1){
      return 1;}
    else {
      return (Math.pow(2.0, n) +1) + recurSum(n-1);}
}
}

Thanks.

This is because you are using n instead of num in your recurSum . n is a static variable that never changes; you should remove it. num , on the other hand, is a parameter that you pass to recurSum ; its value decreases as you go down the levels of recursive invocations, eventually hitting 1 and letting you exit:

public static double recurSum (double num) {
    if (num==1) {
        return 1;
    } else {
        return (Math.pow(2.0, num) +1) + recurSum(num-1);
    }
}

Never use "==" with double because of precision problems, so your recursion is never ending.

Change it to

if (n <= 1)

Also I just noticed that the function takes an argument "num" so "n" is undefined in the function, but I'm assuming that's just a typo here.

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