Perl最大,最小,使用子程序的平均数字

时间:2012-10-17 10:25:49

标签: perl

我在Perl的问题: 使用子例程编写Perl脚本,该子例程接受值列表并将最大,最小和平均值返回给调用程序。

#!/usr/bin/perl

sub large_and_small {   
    my (@numbers);
    @numbers = @_;

    my ($small, $large);
    $large = $numbers[0];
    $small = $numbers[0];

    foreach my $i (@numbers) {

        if ($i > $large) {         

            $large = $i;  
        }        
        elsif ($i < $small) {

            $small = $i;  
        }
    }
    return ($small, $large);
}

sub avg {
    my ($avg);
    my ($total);

    foreach (@test_array) {

        $total += $_;
    }
    $avg = $total/scalar @test_array;
    return $avg;
}

my (@test_array, @ret);
@test_array = (15, 5, 7, 3, 9, 1, 20,1 3, 9, 8, 15, 16, 2, 6, 12, 90);
@ret = large_and_small(@test_array);
print "The Largest value is ", $ret[1], "\n";
print "The Smallest value is ", $ret[0], "\n";
print "The Average value is", avg(@test_array), "\n";

我得到的输出是:

The Largest value is 90
The Smallest value is 1
Illegal division by zero at /tmp/135044395416028.pl line 59.

我在脚本中哪里出错了?请帮忙。谢谢提前

5 个答案:

答案 0 :(得分:4)

我建议您使用核心模块:List::Util,它具有所有功能,您实现为min,max,sum。

#!/usr/bin/perl

use strict;
use List::Util qw(min max sum);

my @test_array = (15, 5, 7, 3, 9, 1, 20, 13, 9, 8, 15, 16, 2, 6, 12, 90);
my $min = min(@test_array);
my $max = max(@test_array);
my $avg = scalar @test_array
        ? (sum(@test_array) / (scalar @test_array))
        : 0;

print "The Largest value is ", $max, "\n";
print "The Smallest value is ", $min, "\n";
print "The Average value is ", $avg, "\n";

答案 1 :(得分:3)

您没有阅读avg中的论据。添加

my @test_array = @_;

您还可以保存一些变量并同时执行声明和分配:

sub large_and_small {
    my @numbers = @_;
    my ($small, $large) = @numbers[0, 0];

    foreach my $n (@numbers) {
        if ($n > $large) {
            $large = $n;
        }
        elsif ($n < $small) {
            $small = $n;
        }
    }
    return ($small, $large);
}

sub avg {
    my @numbers = @_;
    return unless @numbers;  # Prevent Division by zero
    my $total;
    foreach (@numbers) {
        $total += $_;
    }
    return $total / @numbers;
}

答案 2 :(得分:0)

测试数组在main中声明为词法,并直接在函数中使用。要么必须传递给函数,要么删除不建议的词法。

答案 3 :(得分:0)

avg程序没有看到您认为应该看到的@test_array。 相反,它可能会看到空数组。

重写avg如下,它应该有效:

sub avg {
    my @test_array = @_;
    my ($avg);
    my ($total);
    # ...
}

答案 4 :(得分:-1)

看起来这里的分数为零

$avg = $total/scalar @test_array;

你为什么用标量划分?