0

我在 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.

我在脚本中哪里出错了?请帮助。在此先感谢

4

5 回答 5

4

我建议您使用 core module: 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";
于 2012-10-17T10:40:37.273 回答
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;
}
于 2012-10-17T10:33:24.390 回答
0

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

重写avg如下,它应该工作:

sub avg {
    my @test_array = @_;
    my ($avg);
    my ($total);
    # ...
}
于 2012-10-17T10:36:05.250 回答
0

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

于 2012-10-17T10:34:04.607 回答
-1

看起来这里有除零

$avg = $total/scalar @test_array;

你为什么要除以标量?

于 2012-10-17T10:33:37.990 回答