% operator in perl - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

% operator in perl

xiaoyiguoxiaoyiguo Posts: 6Member
I wonder if anybody else had the same problem.

Here I have a very simple perl script:
=======start of code==========
#!/usr/bin/perl
$bY = "254";
$gY = "1.8";
for($r = 0; $r <= $bY; $r = sprintf("%.3f", $r + $gY)) {
print "now it is $r
";
$evenOdd =( $r / $gY ) % 2;
$div =( $r / $gY ) ;
printf "by 2 is %s
", $div;
printf "by 2 remainder is %s
", $evenOdd;
if( (($r / $gY) % 2) == 0) {
print"and it an even number
";
} else {
print"and it an odd number
";
}
}
========end of code========
When I run it:
~/bin/production/t4odd
I got these:
...
now it is 212.400
by 2 is 118
by 2 remainder is 0
and it an even number
now it is 214.200
by 2 is 119
by 2 remainder is 0
and it an even number
now it is 216.000
by 2 is 120
by 2 remainder is 0
and it an even number
now it is 217.800
by 2 is 121
by 2 remainder is 1
and it an odd number
now it is 219.600
by 2 is 122
by 2 remainder is 0
and it an even number
now it is 221.400
by 2 is 123
...

Please note:
212.4 / 1.8 will yield 118, which was divided by 2 would yield a remainder of 0, which is an even number

but 214.2 /1.8 will yield 119, which was divided by 2 would've yielded a remainder of 1, why perl gave a remainder of "0"?

Sign In or Register to comment.