neo1491 has asked for the wisdom of the Perl Monks concerning the following question:

have a bit of a puzzle that i can't seem to work out. Round($Num1/$Num2) Here's what's stumping me... 1. If the sum of ($Num1/$Num2) > 16, then 16 needs to be returned... the number returned has to be a whole number between 1 - 16. 2. I need to round DOWN to the lowest whole number without returning a zero... i'm only using +#'s. Any ideas?

Replies are listed 'Best First'.
Re: Round Down Routine
by Joost (Canon) on Oct 20, 2007 at 02:13 UTC
      I think you mean
      $retval = $number > 16 ? 16 : int($number)
      since yours would return 16 every time?

      int() might return 0, given a value less than 1, though, so POSIX::floor() might still be a better plan.
Re: Round Down Routine
by roboticus (Chancellor) on Oct 20, 2007 at 12:38 UTC
    neo1491:

    Unless I'm grossly misunderstanding your question, you should give your function a better name, as "round" implies a well-known set of behaviors: round up, round down, round nearest. With your extra requirements, a future maintainer could easily be led astray by the name.

    From your description, you want a number to be rounded down to the nearest integer with the additional requirements of:

    (1) never returning a number greater than 16, and
    (2) never returning 0.

    So RoundDownSpecial might be a better name.

    Also, you didn't specify what should be returned instead of 0 in the cases that normal rounding down would return 0. Other requirements are also unspecified, so you could get an entire zoo of behaviors. My candidate for your zoo:

    #!/usr/bin/perl -w use strict; use warnings; sub RoundDownSpecial_bizarro { my $num = shift; my $den = shift; return 7 unless $den+0.0; return 8 unless $num+0.0; my $tmp = int(($num+0.0) / $den); return 16 if $tmp > 16; return 16 if $tmp < 1; return int($tmp); } while (<DATA>) { chomp; my ($n, $d) = split /,/; print join(" ",$n, $d, RoundDownSpecial_bizarro($n, $d)), "\n" +; } __DATA__ 0, 1 10, 0 100, 1 1, 100 2, 1 8, 1 15, 1 16, 1 17, 1
    ...roboticus

    Mechanical Pedant

    UPDATE: Apparently I'm not quite pedantic enough this morning. I missed some parenthesis around the '$num+0.0' clause. Thanks for the catch, FunkyMonk!

Re: Round Down Routine
by thenetfreaker (Friar) on Oct 20, 2007 at 04:33 UTC
    Hello, if you need the lowest whole number, therefore you need only the "integer" value of the floating number.
    $reasult = int($number1/$number2);

    hope it helps ;)
A reply falls below the community's threshold of quality. You may see it by logging in.