1.[12]写一个名为 &total 的子程序,返回一列数字的和。提示:子程序不应当有任何的 I/O 操作;它处理调用的参数,返回处理后的值给调用者。结合下面的程序来练习,它检测此子程序是否正常工作。第一组数组之和我25。
2.[5]利用上题的子程序,写一个程序计算从 1 到1000的数字的和
3.[18]额外的练习:写一个子程序,名为 &above_average,将一列数字作为其参数,返回所有大于平均值的数字(提示:另外写一个子程序来计算平均值,总和除以数字的个数)。
#!/usr/bin/perl
use strict;
my@fred = qw{ 1 3 5 7 9 };
my $fred_total = &total(@fred);
print "The total of \@fred is $fred_total.\n";
print "Enter some numbers on separate lines: ";
my $user_total = &total(<STDIN>);
print "The total of those numbers is $user_total.\n";
sub total
{
my $sum;
for(@_)
{
$sum += $_;
}
return $sum;
}
|
#!/usr/bin/perl
use strict;
my @tmp = 1..1000;
my $sum = &total(@tmp);
print "total is : $sum.\n";
sub total
{
my $sum;
for(@_)
{
$sum += $_;
}
return $sum;
}
|
#!/usr/bin/perl
use strict;
my @fred = &above_average(1..10);
print "\@fred is @fred\n";
print "(Should 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";
sub above_average
{
my $sum = &total(@_);
my $average = $sum / @_;
my @result;
foreach(@_)
{
if($_ > $average)
{
push @result , $_ ;
}
}
return @result;
}
sub total
{
my $sum;
for(@_)
{
$sum += $_;
}
return $sum;
}
|
阅读(814) | 评论(0) | 转发(0) |