我正在用Perl编写一些代码来测试数字并确定它们的所有数字是完全偶数还是完全奇数。 我用$ARGV[0] = 3和$ARGV[1] = 1 。 我遇到了一些麻烦,并在每次外循环通过时添加了行来检查$n的值。 $n的值分别为1,2和2.我想知道为什么$n增加到1。
这是我的代码:
#!/usr/bin/perl use warnings; my $even = 0; my $odd = 0; my $limit = $ARGV[0]; #highest number considered my $places = $ARGV[1]; #number of places in said number for($x = 1; $x <= $limit; $x++){ my @z; my $tot = 0; my $c = $x; for($n = 1; $n <= $places; $n++){ $z[$n] = $c % 2; $tot = $tot + $z[$n]; $c = $c - $z[$n]; if($c == 0){ last; } $c = $c / 10; } print $n; if ($tot == 0) { $even++; }elsif($tot == 1) { $odd++; } } print $even . "\n"; print $odd;我以前没有在Perl中编码,所以如果它有点不优,那就很抱歉。
I'm writing some code in Perl to test numbers and determine if all their digits are entirely even or entirely odd. I ran the program with $ARGV[0] = 3 and $ARGV[1] = 1. I was having some trouble and added the line to check the values of $n each time the outer loop ran through. The values of $n were 1, 2 and 2. I was wondering why $n was increasing past 1.
Here's my code:
#!/usr/bin/perl use warnings; my $even = 0; my $odd = 0; my $limit = $ARGV[0]; #highest number considered my $places = $ARGV[1]; #number of places in said number for($x = 1; $x <= $limit; $x++){ my @z; my $tot = 0; my $c = $x; for($n = 1; $n <= $places; $n++){ $z[$n] = $c % 2; $tot = $tot + $z[$n]; $c = $c - $z[$n]; if($c == 0){ last; } $c = $c / 10; } print $n; if ($tot == 0) { $even++; }elsif($tot == 1) { $odd++; } } print $even . "\n"; print $odd;I haven't coded in Perl before, so sorry if it's a tad inelegant.
最满意答案
循环后打印$n的值。 循环$n的第一次迭代设置为1 ,循环$n递增后( $n++ )然后$n <= $places看到2 > 1因此for循环终止,因此打印2 。
You are printing the value of $n after the loop. The first iteration through the loop $n is set to 1, after the loop $n is incremented ($n++) and then $n <= $places sees that 2 > 1 so the for loop terminates and thus 2 is printed.
更多推荐
发布评论