CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Array

 



perlguru22
New User

Sep 21, 2012, 3:47 PM

Post #1 of 4 (1581 views)
Array Can't Post

Hey guys I am taking an intro to scripting languages and we are using perl but I seem to be stuck in this problem.

"Find the average of the numbers in an array (@nums) of unknown length.

I know it starts something like this

@nums = ();

But I don't know where to go from there.


perlguru22
New User

Sep 21, 2012, 9:25 PM

Post #2 of 4 (1573 views)
Re: [perlguru22] Array [In reply to] Can't Post

#!/usr/bin/perl

@nums = ();
for(@nums)
{
$sum += $_;
}
$size = @nums;
$average = $sum / $size;
print "$average";


Would this be the correct way to do it



BillKSmith
Veteran

Sep 22, 2012, 7:13 AM

Post #3 of 4 (1565 views)
Re: [perlguru22] Array [In reply to] Can't Post

That is a good way to do it without using modules, but I do strongly recommend 'use strict' and 'use warnings' in all perl programs.

Refer to the sum function in the module List::Util to avoid reinventing the wheel.
Good Luck,
Bill


Laurent_R
Veteran / Moderator

Sep 23, 2012, 8:22 PM

Post #4 of 4 (1552 views)
Re: [perlguru22] Array [In reply to] Can't Post

Your overall algorithm looks correct, except that your array is declared as follows:


Code
@nums = ();


meaning that it will be empty. Calculating the average (or mean, or median, or variance, or standard deviation, etc.) on zero value is not very interesting.

You need to find a way to populate @nums with meaningful values. Maybe you could use the rand function or, at worse, hard code some values.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives