在循环中用另一个变量的值替换一个变量的值

时间:2014-09-26 13:19:11

标签: perl

我想用变量值替换c' c'并且' d'变量' a'和' b'分别在下面的例子中,这个过程应该继续进行,以便' n'倍。

#!/usr/bin/perl
my $a = 4;
my $b = 6;
my $c = $a + $b;
my $d = $a * $b;
print "$c\n";
print "$d\n";
$a = $c;
$b = $d;

即。对于循环的每次迭代,计算出的值为' c'并且' d'应该是' a'的新价值。和' b'分别为' n'时间,以便新的价值观' c'并且' d'将生成。我无法替代这些价值观。如何将条件设置为循环“n'次?所需的输出应采用以下形式:

c= val1 val2 val3......valn
d= val1 val2 val3......valn.

3 个答案:

答案 0 :(得分:1)

$a$b变量保留供sort运算符使用。

这将做你想要的事情

use strict;
use warnings;

my ($aa, $bb) = (4, 6);
my $n = 5;

for (1 .. $n) {
   my ($cc, $dd) = ($aa + $bb, $aa * $bb);
   print "$cc\n", "$dd\n\n";
   ($aa, $bb) = ($cc, $dd);
}

<强>输出

10
24

34
240

274
8160

8434
2235840

2244274
18857074560

答案 1 :(得分:1)

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

my ( $sum, $times ) = ( 4, 6 );
my $count = 8;

my @sum;
my @times;
for ( 1 .. $count ) {
    ( $sum, $times ) = ( $sum + $times, $sum * $times );
    push @sum,   $sum;
    push @times, $times;
}

print "c = @sum\n";
print "d = @times\n";

输出:

c = 10 34 274 8434 2244274 18859318834 42320461010388274 798134711765191824044221234
d = 24 240 8160 2235840 18857074560 42320442151069440 798134711722871363033832960 33777428948505262401578369250143488058711040

答案 2 :(得分:0)

这应该有效:

#!/usr/bin/env perl

## Don't use $a and $b, they are special variables
## used in sort().
my $foo=4;
my $bar=6;

## The number of iterations
my $n=5;

## These arrays will hold the generated values
my (@sums, @products);

## Use a for loop
for (1 .. $n) {
    my $sum=$foo+$bar;
    my $product=$foo*$bar;
    ## save the results in an array to print later
    push @sums, $sum;
    push @products, $product;
    $foo=$sum;
    $bar=$product;

}
print "Sum=@sums\nProduct=@products\n";