几道子程序题目

2011-01-27 wcdj

 

【题目1】
写一个名为total的子程序,它可以返回给定列表中数字相加的总和。(提示:该子程序不需要执行任何I/O,它只需要按要求处理它的参数并给调用者返回一个值就行了。)
sub total { my $sum=0;# 私有变量 foreach(@_) { $sum += $_; } $sum; } my @a=qw{1 3 5 7 9}; my $a_total=total(@a); print "The total of /@a is $a_total./n"; print "Enter some numbers on separate lines:/n"; my $user_total=total(<STDIN>); print "The total of those numbers is $user_total./n";

 

【题目2】
写一个名为&above_average的子程序,当给定一个包含多个数字的列表时,返回其中大于这些数的平均值的数。(提示:另外写一个子程序,通过用这些数的总和除以列表中数字的个数来计算它们的平均值。)
sub total { my $sum=0;# 私有变量 foreach(@_) { $sum += $_; } $sum; } sub average { if (@_ == 0) {return} my $cnt = @_; total(@_)/$cnt; } sub above_average { my $average=average(@_); my @res; foreach (@_) { if ($_ > $average) { push @res, $_; } } #print "/@res: @res/n";# debug used @res; } my @a=above_average(1..10); print "/@a is @a/n";# @a is 6 7 8 9 10 print "(Should be 6 7 8 9 10)/n"; my @b=above_average(100,1..10); print "/@b is @b/n";# @b is 100 print "(Should be just 100)/n";

 

【题目3】
写一个名为greet的子程序,当给定一个人名作为参数时,打印出欢迎他的信息,并告诉他前一个来宾的名字:
greet("wcdj");
greet("gerry");
按照表达式的顺序,它应该打印出:
Hi wcdj! You are the first one here!
Hi gerry! wcdj is also here!
use 5.010; greet("wcdj"); greet("gerry"); sub greet { if (@_ != 1) {return} state $last_person; my $name = shift(@_); #my $name = shift; # ok print "Hi $name! "; if (defined($last_person)) {# 注意判断 print "$last_person is also here!/n"; } else { print "You are the first one here!/n"; } $last_person = $name; }

 

【题目4】
修改题目3,告诉所有新来的人,之前已经迎接了哪些人:
greet("wcdj");
greet("gerry");
greet("yj");
按照表达式的顺序,它应该打印出:
Hi wcdj! You are the first one here!
Hi gerry! I've seen: wcdj
Hi yj! I've seen: wcdj gerry
use 5.010; greet("wcdj"); greet("gerry"); greet("yj"); sub greet { if (@_ != 1) {return} state @last_person;# use list my $name = shift(@_); #my $name = shift; # ok print "Hi $name! "; if (@last_person) { # 注意判断 print "I've seen @last_person/n"; } else { print "You are the first one here!/n"; } push @last_person, $name; }

 

 

你可能感兴趣的:(几道子程序题目)