在循环外累积变量(padre perl)

时间:2014-12-04 01:40:57

标签: perl

$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。到目前为止我所有的数字和数字都是平方显示的

1 个答案:

答案 0 :(得分: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来声明变量的原因。
  • 在这种情况下,for循环实现更清晰,更容易理解。例如,查看while循环,很难分辨它的开始位置或$num如何变更。 for声明使您可以轻松查看所有这些内容。循环从1到50,for循环处理递增。
  • 它的标准使用&#34; C&#34;样式花括号而不是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";