[d]求perl 中位数函数
本帖最后由 fibbery 于 2012-09-29 10:03:49 编辑 RT
输入@list数组,输出$mid
ths.
-------------------
Double行动:
原帖分数:20
帖子加分:20
[解决办法]
#! /usr/bin/perl -w
use strict;
use 5.010;
sub mid
{
my @list = sort @_;
my $count = @list;
if( $count == 0 )
{
return 0;
die "怎么办?";
}
return $list[($count-1)/2];
}
say mid( 3, 9, 8 );
say mid( 3, 7, -5, -11 );
say mid( -5 );
say mid();
sub mid{
my @list = sort{$a<=>$b} @_;
my $count = @list;
if( $count == 0 )
{
return undef;
}
if(($count%2)==1){
return $list[int(($count-1)/2)];
}
elsif(($count%2)==0){
return ($list[int(($count-1)/2)]+$list[int(($count)/2)])/2;
}
}