$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。到目前为止,我只看到了显示的数字和数字的平方
发布于 2014-12-04 10:39:14
你只需要两个变量来表示你的总数:
# 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。在这种情况下,您应该得到一本关于现代Perl的好书。
使用use strict;和use warnings;的
my来声明变量的原因。for循环实现更清晰,也更容易理解。例如,查看您的while循环,很难判断它从哪里开始,或者$num是如何改变的。for声明使得查看所有这些内容变得很容易。循环从1到50,for循环处理incrementing.样式的花括号(即,与while、for或if Java的第一行相同的第一个括号
下面是一种更现代的编写程序的方法:
#! /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";https://stackoverflow.com/questions/27284838
复制相似问题