A Balanced Introduction to Computer Science, 3rd Edition David Reed ...

Report 4 Downloads 73 Views
A Balanced Introduction to Computer Science, 3rd Edition David Reed Chapter Seven: Functions and Randomness A. Predefined JavaScript Functions 1. Functions are identified by name with the inputs to the function paced in parentheses a. A unit of computational abstraction b. Example: to convert a string to its corresponding number, add parseFloat function and obtain value c. Calling – applying a function to inputs i. Return value – output of the function ii. Example: amount=parseFloat(document.getElementById(‘amoun tBox’).value); 2. Math Functions a. Prefix is Math. i. Signifies that functions are a part of a library of mathematical routines ii. Example: Math.sqrt (gives square root) Math.max (gives largest of 2 inputs) 3. Raising Numbers to a Power a. Math.pow (2, 3) returns 23=8 i. Can include negative exponents 4. Generating Random Numbers a. A function is a mapping from some number of inputs to a single output b. Math.random has no inputs i. Pseudorandom results: the function uses an algorithm to generate seemingly random values from within the range [0,1) ii. To adjust the range, lpace Math.random in a function (2 * Math.random() makes the range 0 to 2) c. Useful for random chance such as selecting a random image each time the page is loaded or simulating rolling dice B. Simple User-Defined Functions 1. Function minimize the amounts of detail that a programmer must keep track of a. Functions help minimize the length/complexity of code b. Predefined functions represent a collection of useful, general, purpose abstractions 2. User-Defined Functions – individual programmers can construct new abstractions by defining their own functions a. Simple form: function FunctionName() //Assumes: any assumptions about the function

//Results: description of action performed { statements to be executed } i. Preconditions - //Assumes: ii. Postconditions- //Results: b. This is placed in the head of the page: <script type=”text/javascript” src=”javascript.js”> 3. Functions that Simplify a. Functions are only useful when more than 1 action is taking place (like in a button) C. Randomness in a Page 1. Math.random controls random elements in a page a. Example: simulated dice or random slide show