Hier noch eine etwas elegantere Lösung zur Aufgabe 3e:
// save as fib.java
public class fib {
static public int fib(int n) {
int f_old = 1, f_current = 0;
for( int i = 0 ; i < n ; i++ ) {
int f_old_old = f_old;
f_old = f_current;
f_current = f_old_old + f_old;
}
return f_current;
}
static public void main( String[] args ) {
// small test
for( int i = 0 ; i < 10 ; i++ ) {
System.out.println( fib(i) );
}
}
}
[/sourcecode]
Was ist der Trick? :)
Tags: Blatt 6, Fibonacci-Folge, iterativer Ansatz
You must be logged in to post a comment.
Zeile 6,7
ist es nicht fehlerhaft wenn die Variable int f_old_old MEHRFACH initialisiert wird?
bin neu in java-
Nein 🙂
Die Variable wird in einem Scope definiert, der bei jeder Schleifeniteration neu betreten wird. Siehe dazu “Scopes (Bindungsbereiche)” im 6. Foliensatz oder ein beliebiges Java-Buch.