首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在循环外累加变量(padre perl)

在循环外累加变量(padre perl)
EN

Stack Overflow用户
提问于 2014-12-04 09:40:57
回答 1查看 139关注 0票数 0
代码语言:javascript
复制
$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。到目前为止,我只看到了显示的数字和数字的平方

EN

回答 1

Stack Overflow用户

发布于 2014-12-04 10:39:14

你只需要两个变量来表示你的总数:

代码语言:javascript
复制
# 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.
  • It's标准,使其使用"C“样式的花括号,而不是statements).

样式的花括号(即,与whileforif Java的第一行相同的第一个括号

下面是一种更现代的编写程序的方法:

代码语言:javascript
复制
#! /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";
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27284838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档