PDA

View Full Version : how to write javascript code for this function....

university
07-05-2011, 02:56 PM
write a function that when called will ask the user for a series of numbers to be entered 1 at a time and then calculates their sum,their average,and their average rounded up then output the results.

for example the average of a series of numbers is found by adding the numbers together and dividing by the amount of numbers entered (so the average of 2,5,1 and 7 is equal to (2+5+1+7)/4=15/4=3.75).

devnull69
07-05-2011, 03:48 PM

Philip M
07-05-2011, 04:29 PM
Blatant homework!! See Forum Rule 1.5

It is not really in your best interests that others do all or most of your homework for you. Your teacher may gain a false and exaggerated idea of your programming capabilities and so not offer you the support you need. Also, if you hand in other people's work which you do not completely understand, then you will start to fall behind and your difficulties will increase. Finally, there is a limit to the number of times that you can take your pitcher to this well!

Hamza7
07-05-2011, 05:04 PM
Here is the code, I made my best efforts to make it short and simplified as much as possible:

/*----------------------------------Setting section-------------------------------------------*/
var Request = {};
//Set the message to dispaly:
Request.message = "Enter a series of numbers to calculate the average (comma separated):";
//Set the (optional) default example:
Request.example = "2,5,1,7";
//Set parsing type: "float" (for numbers with floating decimal point) or "int" (for integers):
Request.parsingType = "int";
//Set rounding setting (an natural number, ex: 2, 3, 5, 8...etc):
Request.round = 2;
/*--------------------------------------Function section---------------------------------------*/
function parse(String,type){if(type=="float")return parseFloat(String); else if(type="int")return parseInt(String);}
//The main function:
function calculateAvg(){
var numSeries = prompt(Request.message,Request.example||"");
var numArray = numSeries.split(/\s*,\s*/);
var result = 0;
//Calculating the sum:
for (var num = 0;num<numArray.length; num++)result+=parse(numArray[num],Request.parsingType);
//Calculating the average:
result = result/numArray.length;
//Rounding the result:
result = result.toFixed(Request.round);
//Showing the result:
//Returning the value:
return result;}