$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。到目前为止我所有的数字和数字都是平方显示的
答案 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
循环处理递增。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";