in reply to Passing Variables
################################################### # # # 2/24/21 # # Program takes finds the average in an # # array and lists out the numbers that were # # above the average found. # # # ################################################### ### Limitations - added 3/1/2021 ### This code will throw a fatal "Illegal division by zero" ### error if @numbers doesn't contain at least one element. my @numbers = qw(4 12 18 21 35); my $average = find_average(@numbers); print "The average found for this list is: $average \n" ; my @above_avg = above_average($average, @numbers); print "The numbers that were found above average are: @above_avg \n +"; sub find_average { my @nums = @_; my $sum; foreach my $num (@nums) { $sum += $num; } my $avg = $sum / @nums; return $avg; } sub above_average { my ($average_num, @nums) = @_; my @final_list; foreach my $num (@nums) { if ($num > $average_num) { push @final_list, $num } } return @final_list; } __END__ PRINTS: The average found for this list is: 18 The numbers that were found above average are: 21 35
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Passing Variables
by jdporter (Paladin) on Feb 25, 2021 at 22:40 UTC | |
by Marshall (Canon) on Feb 25, 2021 at 23:38 UTC | |
by GrandFather (Saint) on Feb 28, 2021 at 23:29 UTC | |
by Marshall (Canon) on Mar 13, 2021 at 19:41 UTC | |
by GrandFather (Saint) on Mar 14, 2021 at 20:04 UTC | |
by GrandFather (Saint) on Mar 01, 2021 at 00:40 UTC | |
Re^2: Passing Variables
by catfish1116 (Beadle) on Mar 01, 2021 at 20:11 UTC | |
by Marshall (Canon) on Mar 02, 2021 at 21:05 UTC |