in reply to Re^5: why is my for loop using modulo giving me a weird output
in thread why is my for loop using modulo giving me a weird output

I used "use integer;" wouldn't this be correct? or should I add the int while doing the operation $i%5.

use strict; use warnings; use integer; use constant number => 5;

if I have to add this here, what situation am I avoiding?

I don't quite understand this

to chop off the fractional component for $quo
print "this is the quotient",int $i/5,"\n";

Replies are listed 'Best First'.
Re^7: why is my for loop using modulo giving me a weird output
by ww (Archbishop) on Jun 28, 2015 at 11:35 UTC

    re "use integer" tells Perl "to use integer arithmetic instead of floating point" (see http://perldoc.perl.org/integer.html ) -- it's a pragma whereas marinersk's reference is to the function int, which you use correctly in your second code section (tho the output would look better if you included a space before the trailing quote on the text).

    UPDATE: s/correctly/ correctly assuming a value for $i greater than 5. If ($i <5) you'll get zero because int removes fractional the fractional part of a value 0.nnnn / which will look a lot like 5%5. (see -- on your own CLI -- perldoc -f int).

Re^7: why is my for loop using modulo giving me a weird output
by marinersk (Priest) on Jun 29, 2015 at 14:29 UTC

    See for yourself:

    #!/usr/bin/perl use strict; my $i = 1; my ($quo1, $rem1) = ($i/5, $i%5); #need to understand modulo print "Without int: Quotient = [$quo1], Remainder = [$rem1]\n"; my ($quo2, $rem2) = (int($i/5), $i%5); #modified to use int print " With int: Quotient = [$quo2], Remainder = [$rem2]\n"; exit; __END__

    Results:

    D:\PerlMonks>modulo1.pl Without int: Quotient = [0.2], Remainder = [1] With int: Quotient = [0], Remainder = [1] D:\PerlMonks>