====== Mögliche Lösungen um Funktionswerte in Tabellen ausgeben zu können ====== ===== Fortran ===== program main implicit none call tabelle (-20, 20, 1); end program subroutine tabelle ( start, endw, step ) implicit none integer start, endw, step integer k if (step .LT. 1) then step = 1 endif ! Tabellenkopf write (*,*) "+-------------------+" write (*,*) "| x | y |" write (*,*) "+-------------------+" ! x-y-Wertepaare ausgeben do k=start, endw, step write (*, '(1X,2H| ,I7,3H | , I7, 2H |)') k, (2*(k**2) + 4*k + 3) enddo write (*,*) "+-------------------+" end subroutine ==== Zusatzaufgabe ==== program main implicit none external xsquare call tabelle (xsquare, -20, 20, 1); end program integer function xsquare ( x ) integer x; xsquare = x**2; return; end function integer function myfunc ( k ) implicit none integer k myfunc = (2*(k**2) + 4*k + 3) end function subroutine tabelle ( f, start, endw, step ) implicit none integer start, endw, step, f integer k if (step .LT. 1) then step = 1 endif ! Tabellenkopf write (*,*) "+-------------------+" write (*,*) "| x | y |" write (*,*) "+-------------------+" ! x-y-Wertepaare ausgeben do k=start, endw, step write (*, '(1X,2H| ,I7,3H | , I7, 2H |)') k, f(k) enddo write (*,*) "+-------------------+" end subroutine ===== C ===== #include void table ( int start, int endw, int step ) { printf ("+-------------------+\n"); printf ("| x | y |\n"); printf ("+---------+---------+\n"); if (step < 1) step=1; for (int i=start; i<=endw; i+=step) { printf ("| %7d | %7d |\n", i, (2*(i*i)+4*i+3)); } printf ("+---------+---------+\n"); } int main () { table ( -20, 20, 1); } ==== Zusatzaufgabe ==== #include int xsquare ( int i ) { return i*i; } void table ( int start, int endw, int step, int (*myfunc) (int) ) { printf ("+-------------------+\n"); printf ("| x | y |\n"); printf ("+---------+---------+\n"); if (step < 1) step=1; for (int i=start; i<=endw; i+=step) { printf ("| %7d | %7d |\n", i, myfunc(i)); } printf ("+---------+---------+\n"); } int main () { table ( -20, 20, 1, xsquare); } ===== Rust ===== // x is borrowed here fn fn1 ( x: &i32 ) -> i32 { return 3*x*x + 4*x + 3i32; } fn fn2 ( _x: &i32 ) -> i32 { return 1; } // takes an x and a function, which takes an integer and returns an integer fn call_fn ( x: &i32, fct: &dyn Fn(&i32)->i32 ) -> i32 { return fct(x); } fn main() { let vals = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]; // {} inserts a value, :>width$ inside specifies how this value is presented, // -> its aligned to the right (>), the parameter "width" specifies how many spaces are emitted. println!("{:>width$} | {:>width$} | {:>width$}", "x", "fn1(x)", "fn2(x)", width=10); println!("-----------+------------+-----------"); // using a borrowed vals here also makes x borrowed. for x in &vals { println!("{:>width$} | {:>width$} | {:>width$}", x, call_fn( x, &fn1 ), call_fn( x, &fn2 ), width=10) } }