|
Below is a sample Test Question and below that an answer to the question. Try to solve it first on your own (no peeking too early!!) Use the TestTemplate from the Class4 and rewrite the findaverage function.
Test Question: Using the TestTemplate program, write a JavaScript fuctions to enter numbers from a textbox until the user enters stop. Print the average of all numbers entered that are BETWEEN the highest number entered and the Average of all numbers entered.
For example, suppose you entered: 1,2,3,4,5,6,7,8,9 Your function would calculate the average as 5, the high value as 9, then output the average of 6, 7, and 8 (the numbers between 5 and 9) so your answer would be 7
Answer below. Your code will be in red.
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Program with Arrays Template</title>
<script type = "text/javascript"> <!-- var a = new Array( 100 ); // create an Array var count = 0; function buttonPressed() { var searchKey = searchForm.inputVal.value;
if ( searchKey == "stop" ) findAverage(); else { a[count] = parseInt(searchKey); count++; searchForm.inputVal.value = ""; } } function findAverage( ) { var sum = 0; var avg = 0; var hi = 0; var c2 = 0; for ( var n = 0; n < count; ++n ) sum = sum + a[n]; avg = sum/count;
for (var n = 0; n < count; ++n) { if ( a[n] > hi ) hi = a[n]; } sum = 0; // reset sum to 0. old sum is sum of all entries for (var n = 0; n < count; ++n) { if ( a[n] > avg ) if ( a[n] < hi ) { sum = sum + a[n]; c2 = c2 + 1; // could say c2++ } }
searchForm.result.value = sum/c2 } // --> </script>
</head>
<body> <form name = "searchForm" action = ""> <p>Enter integer score or stop to exit<br /> <input name = "inputVal" type = "text" /> <input name = "search" type = "button" value = "Add" onclick = "buttonPressed()" /><br /></p>
<p>Result<br /> <input name = "result" type = "text" size = "30" /></p> </form> </body> </html>
|