Hello there , I have been playing with Perl and found myself in a bit of a situation. I did read about it on different sites (perlmeme , perlmonks , etc) but could not figured what its wrong with my code.
request :
Quote:
Extra credit exercise: write a subroutine, called &above_average, that takes a
list of numbers and returns the ones that are above the average (mean). (Hint: make
another subroutine that calculates the average by dividing the total by the number
of items.) Try your subroutine in this test program.
|
my failed attempt :
Code:
#!/usr/bin/perl
use strict;
my @fred = above_average(1 .. 10);
print "\@fred is @fred. \n";
print "shoud be 6 7 8 9 10. \n";
my @barney = above_average(100, 1..10);
print "\@barney is @barney\n";
print "(Should be just 100)\n";
my $sum_fred = sum(@fred);
print "sum of fred is $sum_fred \n";
my $sum_barney = sum(@barney);
print "sum of barney is $sum_barney \n";
sub sum {
my $sum = 0;
foreach (@_) {
$sum += $_ ;
}
$sum;
}
sub above_average {
my $average = ( (&sum(@_)) / ($#_));
my @other = "";
foreach (@_) {
if ($average < $_) { push (@other, $_)};
}
@other;
}
the output i get :
Code:
@fred is 7 8 9 10.
shoud be 6 7 8 9 10.
@barney is 100
(Should be just 100)
sum of fred is 34
sum of barney is 100
Sum of fred should be 55 and sum of barney should be 77.5 [77 if its truncated to the lower integer I think]. I might be to tired right now to see my mistake, so if anyone spots it please let me know.
Thanks in advance.
PS : Its not a homework , its just an exercise I'm trying to do from "Learning Perl", I check the appendix for the answer but I wanted to try it this way too, if possible.