Moin Leute,
ich arbeite derzeit an einer Aufgabe, in der ich die Fibunacci-Folge rekursiv berechnen muss.
Mein Problem dabei ist, dass ich immer einen Stack Overflow bekomme.
Interessant wird dabei die if-abfrage (i<n):
ich arbeite derzeit an einer Aufgabe, in der ich die Fibunacci-Folge rekursiv berechnen muss.
Mein Problem dabei ist, dass ich immer einen Stack Overflow bekomme.
Interessant wird dabei die if-abfrage (i<n):
Java:
public static void main(String[] args) {
int n;
int summand1 = 1,summand2 = 1;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.printf("Bis zu welchem Element soll die Fibunacci Folge berechnet werden?");
n = input.nextInt();
fibunacci(n,summand1,summand2);
}
public static int fibunacci (int n, int summand1, int summand2) {
int ergebnis;
int r_tiefe = 0,i = 0,m;
m = n - 1;
i++;
if (n == 1) {
ergebnis = summand1;
System.out.printf("n%d: %d Ergebnis: %d Rekursionstiefe: %d",n,summand1,ergebnis,r_tiefe);
return(1);
}
if (n == 2) {
ergebnis = summand1 + summand2;
System.out.printf("n%d: %d n%d: %d Ergebnis: %d Rekursionstiefe: %d",m,summand1, n,summand2,ergebnis,r_tiefe);
return(1);
}
if (i < n) {
ergebnis = summand1 + summand2;
System.out.printf("n%d: %d n%d: %d Ergebnis: %d Rekursionstiefe: %d Funktionsaufrufe: %d",m,summand1, n,summand2,ergebnis,r_tiefe,i);
r_tiefe++;
summand1 = summand2;
summand2 = ergebnis;
fibunacci(n,summand1,summand2);
}
else {
return(-1);
}
return(1);
}
}
Zuletzt bearbeitet von einem Moderator: