2014-09-26 133 views
0

我想在下面的示例中分別將變量'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」的計算值應該是「一」和「b」分別爲的新值「N」次,使得新值'c'和'd'將被生成。我無法取代這些值。如何將條件設置爲循環'n'次?所期望的輸出應爲以下形式:

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

它只是一個例子,也可以用一些其他的變量。 @KalanidhiM。 – swapnil90 2014-09-26 13:25:00

回答

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 "[email protected]\[email protected]\n"; 
+0

很少有必要使用C風格的for循環。在這種情況下,編寫'for(1 .. $ n){...}' – Borodin 2014-09-26 13:56:52

+0

@Borodin會更簡單,謝謝,好點。回答編輯。 – terdon 2014-09-26 14:01:20

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,但請注意,OP似乎希望輸出「的格式爲:c = val1 val2 val3 ...... valn d = val1 val2 val3 ...... valn。」 – terdon 2014-09-26 14:03:05

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