Show pageOld revisionsBacklinksBack to top This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== Aufgaben zu for/if in JavaScript ====== Alle Aufgaben sollen die Ausgabe auf die Konsole produzieren. Damit das Programm gleich beim Laden der Web-Seite augeführt wird, können Sie wie folgt vorgehen: <code javascript> function aufgabe() { var wert = 123; console.log(`wert=${wert}. Praktisches Ausgeben von Variablen mit backticks`); } aufgabe(); </code> oder fancy, ohne globale Variable in einer anonymen Funktion: <code javascript> (function() { var wert = 123; console.log(`wert=${wert}. Praktisches Ausgeben von Variablen mit backticks`); })(); // Anonym definierte Funktion gleich aufrufen </code> <WRAP todo> Simulieren Sie exponentielles Wachstum mit dem Anfangswert von 2000 und Zunahme 1.1 pro Periode während 10 Perioden. </WRAP> <WRAP todo> Bestimmen Sie 100'000 mal einen zufälligen Punkt im Einheitsquadrat und zählen Sie, wie oft dieser im Einheitskreis liegt. Schätzen Sie damit die Kreiszahl $\pi$ ab. </WRAP> <hidden Lösungsvorschlag> <code javascript> // Array mit anonymen Funtionen, // die am Schluss nacheinander aufgerufen werden. [ function() { // Exponetielles Wachstum var count = 2000; var growth = 1.1; var periods = 10; console.log("Exponentielles Wachstum"); for (let i=0; i<periods; i++) { console.log(`${i}: ${count*growth**i}`); } }, function() { // pi Würfeln var count = 100000; var drin = 0; console.log("Pi würfeln"); for (let i=0; i<count; i++) { if (Math.random()**2+Math.random()**2<1) { drin++; } } var piapprox = drin/count*4; console.log(`Von ${count} liegen ${drin} Punkte im Kreis, Schätzung pi=${piapprox}`); }, ].map(f=>f()); // Jede Funktion im Array (heisst jeweils f) einmal aufrufen mit f(). </code> </hidden> lehrkraefte/blc/informatik/ffprg1-2021/js/ex-for-if.txt Last modified: 2021/04/30 16:19by Ivo Blöchliger