2014-12-04 43 views
0
$num = 1; 
print "   Number\n"; 
print "Number Squared\n"; 
while ($num <= 50) 
{ 
    $numSquared = $num * $num; 
    printf ("%3d %6d\n",$num,$numSquared); 
    $num = $num + 1; 
} 

print "End of Program\n"; 
exit 0; 

我想創建一個變量,它將累積循環內的數字和數字的總和。這是使用padre perl。所有我迄今是數字和數字的平方顯示累積變量out一個循環(padre perl)

回答

1

所有你需要的是爲您彙總了兩個變量:

# Your two variables to track the sums: 
$total_sum  = 0; 
$total_square_sum = 0; 

$num = 1; 
print "   Number\n"; 
print "Number Squared\n"; 
while ($num <= 50) 
{ 
    $numSquared = $num * $num; 
    printf ("%3d %6d\n",$num,$numSquared); 
    $num = $num + 1; 

    # Summing with those variables 
    $total_sum  += $num; 
    $total_square_sum += $numSquared; 

} 
print "Sum of numbers: $total_sum Sum of Squares = $total_square_sum\n"; 

我想你正在學習的Perl。在這種情況下,您應該閱讀Modern Perl的一本好書。

  • 使用use strict;use warnings;可以捕捉到很多錯誤。這就是他使用my來聲明變量的原因。
  • A for在這種情況下的循環實現更清潔並且更容易理解。例如,看着你的while循環,很難判斷它開始的位置或$num的變化。 for聲明可以很容易地看到所有這些事情。循環從1到50,並且for循環處理增量。
  • 使用「C」樣式大括號而不是Java樣式大括號(即與whileforif語句的第一行在同一行上的第一個括號)使用標準。

這裏是寫你的程序的現代的方式:

#! /usr/bin/env perl 
# 

use strict;    # Lets you know when you misspell variable names 
use warnings;   # Warns of issues (using undefined variables 
use feature qw(say); 

my $total_sum  = 0; 
my $total_square_sum = 0; 

print "   Number\n"; 
print "Number Squared\n"; 
for my $num (1..50) { 
    my $numSquared = $num * $num; 
    printf ("%3d %6d\n",$num,$numSquared); 

    $total_sum  += $num; 
    $total_square_sum += $numSquared; 

} 
print "Sum of numbers: $total_sum Sum of Squares = $total_square_sum\n"; 
+0

我已經刪除贊成你的我的。你可能想刪除參考:) – ikegami 2014-12-04 02:54:38