JavaScript - Help Need To Find An Average
hi
I need to find the average number in javascript. I have been working on it for a while but i am getting no where yes i am new to javascript and to be honest it is doing my blonde headed brain in. can someone please take a look at it and advise me on what i am doing wrong. it is the only bit of javascript that i have to do in the course but it carries a high mark of which i can not afford to lose Any way the question is : "Write code to calculate the average height and write it out in the browser window" Code: <HEAD> <TITLE> average </TITLE> <SCRIPT LANGUAGE = "JavaScript"> //Experimental results of Table 1 stored in arrays. var Height = [15,16,17,18,19]; var Number = [2,1,6,4,2]; //Part (ii). //Write code to declare and initialise new array to represent the third row of the table. var avg = new Array(5) var avg = ["60","80","187","180","114"] ; avg[0] = "60"; avg[1] = "80"; avg[2] = "187"; avg[3] = "180"; avg[4] = "114"; //Part (iv). //Write code to calculate the average height and write it out in the browser window. avg = 0; for (var count = 1; count <= 5; count = count + 1) Array.average = function(){ var avg = 0; for(var a = 0; a < this.length; a++){ avg += this[a]; } return avg / this.length; }; document.write('average height is ' +avg + '<br>'); </SCRIPT> </HEAD> <BODY> </BODY> </HTML> sorry for my ignorance thanks in advance kelly XXXXX Similar TutorialsSo I am making a function that takes numbers and when you enter a letter than it's supposed to skip to the if statement and give the average. The problem is that it doesn't seem to add the number to total on each loop. the first code is what I am working with. I was supposed to take a While loop and turn it into a do-while loop. The second peice of code is the original while loop. } Code: var finding_average = function() { var total = 0, count = 0, number; alert("Enter the numbers to average. Enter any non-number to stop."); do { number = parseInt( prompt("Enter a number") ); total = total + number; count++; } while ( !isNaN(number) ); var average = total / count; if ( isNaN(average) ) { alert("You didn't enter any numbers."); } else { alert("The average is: " + average); } Code: var finding_average = function() { var total = 0, count = 0, number; alert("Enter the numbers to average. Enter any non-number to stop."); number = parseFloat( prompt("Enter a number") ); while ( !isNaN(number) ) { total += number; count++; number = parseFloat( prompt("Enter another number") ); } var average = total / count; if ( isNaN(average) ) { alert("You didn't enter any numbers."); } else { alert("The average is: " + average); } } Hello, I'm new here and a newbie to the world of java script. I am taking a CIT class and we just moved on to java script which i am having trouble with. My assignment is to calculate the average, number of passed, and number of failed grades according to this list (65, 80, 85, 55, 90, 70, 62, -1) where it terminates at -1 and the passing grade is >=70. Any help is appreciated! I need to allow a user to enter 3 values, then display the average between them... I am having some real issues with the average, Thanks! var quiz1 = prompt("What is the score of your first quiz?", "") document.write("Return Value: "+quiz1, '%',("<br />")); var quiz2 = prompt("What is the score of your second quiz?", "") document.write("Return Value: "+quiz2, '%',("<br />")); var quiz3 = prompt("What is the score of your third quiz?", "") document.write("Return Value: "+quiz3,'%',("<br />")); average= ("quiz1"+"quiz2"+"quiz3") /3 document.write(average,("<br />")); helow to every one im new here....i hope im welcome here can i ask how to make this problem? input 20 number and print the average of the numbers....any one can help me please... Hi i need to find the highest average from all of the averages entered in this code, but i have to use an if statement only, no arrays. Could some one help please? Code: // ** Work out average ** // average= readingSum/totalReadings // ** Put average into a category and display everything ** // if(average<5) { catergory1=alert("Location is " + region + "\nNumber of weekly readings taken is " + totalReadings + "\nTotal of readings is" + readingSum + "\nAverage is" + average + "\nLocation is Dry"); } else if(average>=5 && average<20) { catergory2=alert("Location is " + region + "\nNumber of weekly readings taken is " + totalReadings + "\nTotal of readings is" + readingSum + "\nAverage is" + average + "\nLocation is Normal"); } else if(average>20) { catergory3=alert("Location is " + region + "\nNumber of weekly readings taken is " + totalReadings + "\nTotal of readings is" + readingSum + "\nAverage is" + average + "\nLocation is Wet"); } // ** Find Highest average ** // Thanks. I've now got to form an average of snowfall inputs, taken from looped prompts, however I'm not allowed to use arrays or functions... Almost every example I see uses arrays, such as this one he http://www.codingforums.com/showthread.php?t=4313 Is it possible to not use arrays to form the average? Please describe how to do this in general terms, as was highlighted in that link ^^^ I want to learn, not copy, although one can be derived from the other... What I haveso far, assume all vars have been announced. Code: for (var d=1; d<=numofinputs; d=d+1) { input = prompt("Enter a data input" + d) } Is it possible I'm attempting this in too general a manner? ie, running before I can walk. Hi all, I am in a non-major class called webprogramming working with javascript and I'm having an issue with a specific code wondering if someone could tell me what's wrong! So I am suppose to compute and return the average of all values in a given array named customerBalance, the array holds the amount of "what customers owe my business" (I dont own a business) and each item in the array holds the "customers balance", i also have to use a for() to process the array and calculate the average and divide by customerBalance length, and finally return the average. Here is my code so far <script> function average() { customerBalance for(i=0,i++) sum(customerBalance) total=sum/5 return average; }; </script> I know that this is COMPLETELY wrong, I am not sure on how i start typing the array, please don't be harsh I would really like to know how to do this. Thank you and have a great day Hi, First i don know if im posting at the right place or if you even take request here, feel free to direct me to the right place. What i am looking for is someone to make a simple counter for me. Basically i want that every time i press a certain key on my keyboard it will increase the counter amount and would then divide it by 60 every hour. Actually im looking for it to only show that average and refresh every hour. So it would start at 0 then update after the first hour and so on. (I also need a graphical interface) I have very few knowledge in coding and would very appreciate if someone could do that for me. Thank you ! Reply With Quote 01-10-2015, 11:39 PM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,311 Thanks 82 Thanked 4,754 Times in 4,716 Posts I don't think this is something you would do with JavaScript. I think you need a ".exe" (on Windows) program. And that's a lot more complex. The problem is your request to capture a certain key, presumably no matter what window is at the front. Normally, within a given window, you can only capture a key that is intended for that window. I don't think this is a very easy thing to do. I've written a program which will prompt for a number of cities, Prompt for the name of the city, then prompt for the number of snowfall readings of that city, and then prompt for each of these individual snowfall readings of that city. From this, it adds up each of the individual snowfall readings of that city, and will calculate an average by dividing this figure [the total snowfall] by the total number of readings for that city. This average is used to then classify the city as "not snowy", "mild", or "blizzard". I'm happy to PM my code to anyone willing to help out, as I realise this is a complex structure to visualise perhaps, but I can't post it publicly. I now have to select the city with the highest average, and name it in an alert output. How is this possible. Note, I'm not allowed to use functions or arrays. Prompts, alerts, if-then-else, for and while loops are all I can use. I've been messing with this code for about a couple of hours, and I did everything down to the wire..yet still I am unable to get it to work. When I input the numbers, and click off to the side nothing appears down at the final textarea of the form which is suppose to show the average. I've tried just about everything, sadly all I have to go by is other example codes, and the very intricate instructions which states I must pass the values to the calcAvg() to the second function of performCalc(), which I did, and then I assigned the var calcResult another value. From there I did the return..and after that I'm rather loss as to what to do next to get this code to work, any tips? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Calculation Average</title> <script type="text/html"> /* <![CDATA[ */ function calcAvg() { var calcResult=document.numbers.number1.value + document.numbers.number2.value +document.numbers.number3.value + document.numbers.number4.value + document.numbers.number5.value } function performCalc() { var calcResult = calcResult / 5 return calcResult; } /* This is what I got so far, as you can see I need plenty of help!*/ </script> </head> <H1> Calculate Average of Numbers</H1> <body> <form action="" name="numbers"> <table> <tr> <td> <tr> <td>Enter the five numbers:<br /> </td></tr> <tr><td> <input type="text" name="number1" size="3" onchange="calcAvg()" text="0" /></td> </tr> <tr> <td> <input type="text" name="number2" size="3" onchange="calcAvg()" text="0" /></td> </tr> <tr> <td> <input type="text" name="number3" size="3" onchange="calcAvg()" text="0" /></td> </tr> <tr> <td> <input type="text" name="number4" size="3" onchange="calcAvg()" text="0" /></td> </tr> <tr> <td> <input type="text" name="number5" size="3" onchange="calcAvg()" text="0" /></td> </tr> </table> </form> <form action="" name="averageResult"> <p> Estimate average: <input type="text" name="average" size="5" style="border-style: none; border-color: inherit; border-width: medium; background-color: Transparent" text="0" /></p> </form> </body> </html> This is the script itself - no error messages are generated. Code: <script language="javascript" type="text/javascript"> function getXMLHTTPRequest() { try { req = new XMLHTTPRequest(); } catch(err1) { try { req = new ActiveXObject("Msxm12.XMLHTTP"); } catch(err2) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(err3) { req = false; } } } return req; } var http = getXMLHTTPRequest(); function getCattle(animal_id){ var myurl = 'find_cattle.php'; var CattleValue=animal_id; var modurl= myurl+"?d="+CattleValue; **************the alert returns the correct value from my selection and after than nothing, I never get my alert from the response portion alert("Looking For "+modurl); ******* http.open("GET", modurl, true); http.onreadystatechange=useHttpResponse; http.send(null); } function useHttpResponse(){ ************It never gets to this response alert("Made It To Response"); if (http.readyState == 4) { if(http.status == 200) { var ListValue = http.responseXML.getElementsByTagName("animal_id")[0]; document.getElementsById('cattle_data').innerHTML = animal_id.childNodes[0].nodeValue; } } } </script> thank you Hello, Below is the javascript I'm debugging (or trying to) but just can't see where the error is: The code should send a message "GOOODDD!!!" when the input box is empty (nothing typed in) and should send a message (BAAADD!!!) when a string of theee a's are typed in ("aaa"). The problem is that no matter what I type in the script ALWAYS sends me a "GOOODD!!" message. I guess it is a simple glitch but I just can't figure it out. I'd appreciate any help Thank You. Code: <script language="javascript" type="text/javascript"> <!-- function textCheck(that) { var mytext=document.getElementById("BLABLA") if (mytext == "aaa") alert("BAAAAADDDDD!!!!" + mytext.value); else alert(" GOOOODDDD!!!!" + mytext.value); } --> </script> </head> <body> <form id="form1" method="get" onsubmit="textCheck(this)" /> <input name="BLABLA" size="3" type="text"/> Input Data <br/><br/> <input name="Submit1" type="submit" value="submit" /> </body> </html> function textSize(updown) { var size = Number(readCookie('user-font-size')); if (size == 0) { size = 12; // No Cookie, Set A Default Size Of 12px } size = size + Number(updown); // Adjust The Current Size if (size > 20) { size = 20; } // Stop At 13 if (size < 12) { size = 12; } // Stop At 10 writeCookie('user-font-size', size, 12); // Update The Cookie document.body.style.fontSize = size + 'px'; // Set The Users Text Size } function writeCookie(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = '; expires=' + date.toGMTString(); } else { expires = ''; } document.cookie = name + '=' + value + expires; } function readCookie(name) { name += '='; var cs = document.cookie.split(';'); for (var i = 0; i < cs.length; i++) { var c = cs[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(name) == 0) { //-----------// return c.substring(name.length, c.length); // Gotcha // } //-----------// } //------------// return null; // Failed // } //------------ <img id="plustext" class="zoom-in" alt="Increase text size" src="Zoom-In-icon.png" onclick="textSize (2);" style="cursorointer" /> <img id="minustext" class="zoom-out" alt="Decrease text size" src="Zoom-Out-icon.png" onclick="textSize (-2);" style="cursorointer" /> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vel fringilla arcu. Cras ullamcorper nunc ac sapien gravida ultrices. Curabitur mollis consectetur elit non tempus. Duis blandit luctus feugiat. Nullam eget tellus at quam dapibus tempus in scelerisque ligula. Phasellus turpis ante, tincidunt at aliquam vel, luctus vitae leo. Suspendisse dignissim vehicula est, ac dapibus justo pellentesque eu. </p> cheers hope thats enough code Ant. Hi, I've been trying to code a javascript fonction that uses Window.find and I'm having problems doing exactly what I want. I don't know much of java and I understand that it's not everyone who's willing to do all the work for me so I'm looking for a very kind person here I want it to find a specific string that won't change (so no use to prompt for it) in another existing page that would be loaded in a frame. When the string is found, a sound is played like an alarm. The entire thing should reload every like 5 minutes. That's the easy part. I'm having trouble with the "If found in the frame, play a sound part". I don't think it's pretty hard to do, but hey, I can't do it. As I said earlier, I understand I ask for someone to do the whole thing for me but I'm willing to pay by paypal for the service. Let's say... I don't know, ten bucks should do it. I think I've been clear with what I need but if not, please feel free to ask for more specifications. Thanks for your time. Hi All, I have the date in 2009-10-24 format.can anyone tell how can I get the day of any particular date entered by user. Thanks in advance... This is a function designed to return an array of all elements in "body" with a particular tag name and class name. It works fine up until the if (needles.length == 0); { line, according to my debugging. It seems to fail there though and I can't figure out why. It's probably just some noob error that I've missed but I can't for the life of me find it Thanks in advance for any help, it's greatly appreciated! Code: function getElementsByClassName(tagname, classname) { var haystack = document.getElementById('body').getElementsByTagName(tagname); var needles = []; var i; for (i in haystack) { if (haystack[i].hasClassName(classname)) { needles.push(haystack[i]); continue; } } if (needles.length == 0); { needles = 0; } return needles; } Hello. Please excuse my ignorance but I am not too clued up on javascript. Im hoping someone may be able to help me out here. I have managed to locate a script which will find text on a page, but I have a couple of requests. Firstly the script will only search up. I would like the search box to be at the top of a page but the only way to get it to work correctly is placing it at the bottom of the page. Secondly would some kind soul advise me how to place the script in an external file and then link to it. Thanks in advance. Hello, please tell me where can I find script visible on page www.frendzel.pl (Big picture changing every few second to another from the list on the left)
I am trying to do a title case project and can't figure out where I went wrong. Any help would be appreciated. <!DOCTYPE html> <html lang="en"> <head> <title>Title Case</title> <meta charset="utf-8"> <script type="text/javascript"> function titleCase() { var word = document.forms[0].string.value.split(" "); var cword = ""; for (var i = 0; i < word.length; i++) { cword = cword + word[i].substr(0, 1).toUpperCase() + word[i].substr(1).toLowerCase() + ((i < word.length - 1) ? " " : ""); } return cword; } </script> </head> <body> <h1>Title Case</h1> <form action="" method="get"> <p><input type="text" name="string" /> <input type="button" value="Convert to Title Case" onclick="titleCase()" /></p> </form> </body> </html> Hello, I have recently started a website which tells visitor's IP address, location and others details. I want to add some more functions to it. I found no way to detect visitors Internet Service Provider (ISP) using PHP. I would like to know if there is any way to do so in Javascript. Click the below link to view the site: Show IP Please help me ASAP. Regards, Wasif K. |