Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Oct 2006
    Posts
    32
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Would it be better to make this entire thing a function

    or to just write it out as is.

    Code:
    <html>
      <head>
        <title>CSC Lab 9</title>
      </head>
         <body>
            <script type = "text/javascript">
               var userinput = window.prompt("Enter a set of numbers, separated by spaces", "0 0 1 2 3 4 5 6 7 8 9");
    	   var newarray = userinput.split(" ");
    	   var alength = newarray.length;
    	   
    		function sorting(a, b)
    	          {
    	          return a-b;
    	          }
    	        newarray.sort(sorting);
    
    	   for(i=0;i<alength;i++)
    	      {   
    	        newarray[i] = parseInt(newarray[i]);
    	      }
    	            arsum = 0;
    		for(i=0;i<alength;i++)
    		   {
    		     arsum+= newarray[i];
    		   }
    		    var mean= (arsum/alength);
    	      var median = 0;
               if(alength%2 == 1)
    	      {
    	       median = newarray[parseInt(alength/2)];
    	      }
    	     else
    	       {
    	         var temp1med = newarray[parseInt(alength/2)];
    	         var temp2med = newarray[parseInt((alength/2)-1)];
    	         var median= (temp1med+temp2med)/2
    	       }
    	   var largestfreq = 0;
    	   var largestmode = 0;
    	   var currentfreq = 0;
    	   var currentmode = newarray[0];
    	     for(i=0;i<=alength;i++)
    		{
    		  if(newarray[i] == currentmode)
    		  {
    		  currentfreq++;
    		  }
    		 else
    		 {
    	 	   if (currentfreq > largestfreq)
    			{
    			largestfreq = currentfreq;
    			largestmode = currentmode;
    			}
    		 currentmode = newarray[i];
    		 currentfreq = 1;
    		 }
    	       }
    	     if (currentfreq > largestfreq)
    		{
    		largestfreq = currentfreq;
    		largestmode = currentmode;
    		}
    
     	document.write("Your mean is '+mean+' <br>");
    	document.write("Your median is '+median+' <br>");
    	document.write("Your mode is '+largestmode+' <br>");
    
    
    </script>
    </body>
    </html>

  • #2
    Supreme Master coder! _Aerospace_Eng_'s Avatar
    Join Date
    Dec 2004
    Location
    In a place far, far away...
    Posts
    19,291
    Thanks
    2
    Thanked 1,043 Times in 1,019 Posts
    Maybe not one big function just seperate functions. I was taught that if I wrote a method that the method (function) should do only one thing and it should do it well.
    ||||If you are getting paid to do a job, don't ask for help on it!||||


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •