Search code examples
arraysperl

Perl calculate average from randomly populated array


I have a school assignment I need help with. Now, I know what you're thinking, but my teacher is out of town and hasn't answered my e-mails, and my other classmates have no clue how to solve this problem. A few pointers and tips would be greatly appreciated!

The assignment is this:

We're supposed to create an array, populate it with 20 to 30 random integers in the range of 1-100. Then, by the help of subroutines, we're supposed to calculate the average of these numbers.

The problem occurs when I'm calling the subroutine back, which gives me either answer 0 or the "Illegal division by 0" error. The code I have right now is this:

#! /usr/bin/perl -w

use warnings;
use strict;

# Declaring the scalar variables and arrays.
my @AllNumbers;

# Create random data set of between 20 to 30 measures used for the 100 random intigers.
my $random_number = int( rand( 31 - 20 ) ) + 20;

# Create random data set of 100 intigers.
for ( my $i = 0 ; $i <= $random_number ; $i++ ) {
    $AllNumbers[$i] = int( rand( 100 - 1 ) );
}

# Print the 20 to 30 random numbers (range 1 - 100).
print("Your random numbers are: \n@AllNumbers");

sub average {
    my $ArrayAverage = @_;
    for (@_) {
        my $total += $_;
    }
    return $ArrayAverage / $random_number;
} ## end sub average

# Print the mean/average of the 20-30 numbers.
print( "\n\nThe average of those random numbers is: ", &average, "\n\n" );

Now, as I said, I'd like to solve this problem myself, and I've spent an entire two days with this, but can't seem to solve it no matter what I do. Any tips would be greatly appreciated. P.S. It should be mentioned that we're not supposed to use any modules/plugins.


Solution

  • Nice work, so far! It's almost ok. But you are calling your average function without any parameters (&average). Try it like so:

    sub average{
        my @Array_To_Average = @_; # this is now a local copy of the global @AllNumbers
        my $total = 0;
        for (@Array_To_Average) # iterate over the local copy ...
        { 
            $total += $_; # ...and sum up
        }
        return $total / $random_number;
    
        # instead of $random_number you could also use
        # scalar(@Array_To_Average). That's the number of items
        # in the array, i.e.
        #   return $total / scalar(@Array_To_Average);
    }
    
    print ("\n\nThe average of those random numbers is: ", average(@AllNumbers), "\n\n");
    

    Please omit the & when calling functions. That's very old style. Prefer the style used in most other languages:

    my $result1 = some_function();
    my $result2 = some_other_function($param1, $param2);