如何使这个Perl程序按降序打印?

时间:2016-10-14 14:53:19

标签: perl while-loop integer

此代码有效,但按升序打印。我需要改变整个公式吗?

print "Enter an integer \n";
my $root = <STDIN>; 
my @nums = (100..200);    
my $i = 0;           

# code in while loop executes as long as condition is true 
while ( $i < $#nums ) 
{
    print "$nums[$i]\n",if($nums[$i] % $root == 0); $i++;
}

4 个答案:

答案 0 :(得分:3)

只需将$i设置为$#nums而不是0,然后将其递减--而不是递增。您需要将循环条件更改为$i >= 0(代码中应为$i <= $#nums,否则在输入200时会跳过10

#!/usr/bin/perl
use warnings;
use strict;

print "Enter an integer \n";
my $root = <>;
my @nums = (100 .. 200);
my $i = $#nums;

while ( $i >= 0 ) {
    print "$nums[$i]\n" if $nums[$i] % $root == 0;
    --$i;
}

答案 1 :(得分:2)

有很多方法可以做到这一点...... 并非所有同样好的

#!/usr/bin/env perl

use strict;
use warnings;

run(@ARGV);

sub run {
    my $root = $_[0] // get_root();
    my @nums = (100 .. 200);

    my @functions = (
        sub {
            my ($root, $nums) = @_;
            my $i = @$nums;

            while ($i--) {
                print "$nums->[$i]\n" unless $nums->[$i] % $root;
            }
            return;
        },
        sub {
            my ($root, $nums) = @_;
            for my $n ( reverse @$nums ) {
                print "$n\n" unless $n % $root;
            }
            return;
        },
        sub {
            my ($root, $nums) = @_;
            my $i;

            while ($i++ < @$nums) {
                print "$nums->[@$nums - $i]\n" unless $nums->[@$nums - $i] % $root;
            }
            return;
        },
        sub {
            my ($root, $nums) = @_;
            my @multiples = reverse grep !($_ % $root), @$nums;
            print "$_\n" for @multiples;
            return;
        },
    );

    for my $i ( 0 ... $#functions ) {
        print "=== Function $i ===\n";
        $functions[$i]->($root, \@nums);
    }
}


sub get_root {
    return scalar <STDIN>;
}

答案 2 :(得分:1)

print "Enter an integer \n";
my $root = <STDIN>; 
my @nums = (100..200);
  

@nums = reverse @nums; #Just reverse the arrays

my $i = 0;           

# code in while loop executes as long as condition is true 
while ( $i < $#nums ) 
{
    print "$nums[$i]\n",if($nums[$i] % $root == 0); $i++;
}

可能会帮助你。

答案 3 :(得分:1)

for (my $i = $#nums; $i >= 0; --$i) { ... }

for (my $i = @nums; $i--; ) { ... }

for my $i (reverse 0 .. $#nums)  { ... }

for (1 .. @nums)  { my $i = -$_; ... }   # Or: my $i = @nums-$_;

for my $num (reverse @nums) { ... }