循环递增值的三部分增加超过其限制(Three

编程入门 行业动态 更新时间:2024-10-28 02:22:59
循环递增值的三部分增加超过其限制(Three-part for loop incrementing value increasing past its limit)

我正在用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.

更多推荐

本文发布于:2023-07-16 07:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1125547.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!