所有你需要的是爲您彙總了兩個變量:
# 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樣式大括號(即與
while
,for
或if
語句的第一行在同一行上的第一個括號)使用標準。
這裏是寫你的程序的更現代的方式:
#! /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";
我已經刪除贊成你的我的。你可能想刪除參考:) – ikegami 2014-12-04 02:54:38