Javakurs/Übungsaufgaben/Fibonacci/Musterlösung
< Javakurs | Übungsaufgaben | Fibonacci(Weitergeleitet von Javakurs2007/Fibonacci/Musterlösung)
public class FibonacciNumbers { public static void main(String args[]) { printfibonacci(-1, 8); } /* outputs fibonacci numbers from argument one to argument two */ public static void printfibonacci(int start, int end) { for (int i = start; i < end; i++) { System.out.println("fibonacci(" + i + ") = " + fibonacci(i)); } } /* calculates a fibonacci number of n */ public static int fibonacci(int n) { if (0 == n) { return 0; } if (1 == n) { return 1; } if (n > 1) { return fibonacci(n - 1) + fibonacci(n - 2); } else { System.out.println("Error! Fibonacci undefined for negativ values"); return -1; } } }
Alternative Lösung
public class Fibonacci { public static void main(String[] args) { System.out.print(fibonacci(5)); } public static int fibonacci(int n) { if (n < 0) { System.out.print("Du hast eine negative Zahl eingegeben:"); } else { if (n > 1) { n = fibonacci(n - 1) + fibonacci(n - 2); } } return n; } }