Tugger the SLUGger!SLUG Mailing List Archives

Re: [coders] RubySIG Lesson Code


On Wed Jun 14, 2006 at 12:50:54 +1000, justin randell wrote:
>a php version. (yeah, i know php is considered a dirty word around here ;-) 
>)
>
>* ducks *
>
>transcribed from ruby version:
>
>#! /usr/bin/php
><?php
>$amount = (float) $argv[1];
>
>$remainder = $amount % 5;
^-- I think you need to use fmod here
>$base_amount = $amount - $remainder;
>
>if ($remainder > 2)
>   $x = 5;
>else
>   $x = 0;
>
>print $base_amount + $x . "\n";
>?>
>
>1. php, $argv is an array of command line args, starting at $argv[1]
>(same reason as with python and C).
>2. strings don't have methods :-)
>3. could use php built in function floatval() instead of casting with 
>(float):
>$amount = floatval($argv[1]);

This is interesting, what would be the difference between using floatval()
and using the (float) cast?

4. Things need to be prefixed by a $

>question: why use float and not int?
>
>the ruby, python, and php examples don't work as expected if the
>number supplied to the script is a simple float.
>
>justin@dapper:~/$ ./round5.rb 7.4
>10.0
>
>justin@dapper:~/$ ./round5.py 7.4
>10.0
>
>justin@dapper:~/$ ./round5.php 7.4
>5.4
>(WTF?  in php
>$remainder = $amount % 5;
>returns an int, not a float...)

I think you need:

$remainder = fmod($amount, 5);

(Similar to the C version, '%' operator doesn't work with floats, I'm guessing
that php is doing an automatic type conversion for you? Can anyone confirm?)

Cheers,

Benno