Why does PHP return INF (infinity) for the following piece of code:
<?php
$n = 1234;
$m = 0;
while ($n > 0)
{
$m = ($m * 10) + ($n % 10);
$n = $n / 10;
}
var_dump($m);
?>
The expected result was 4321, but PHP returned INF, float type:
float INF
I wrote the same code in Python and C# and got the expected output - 4321
Python
n = 1234
m = 0
while (n > 0):
m = (m * 10) + (n % 10)
n = n / 10
print m
C#
static void Main(string[] args)
{
int n = 1234;
int m = 0;
while (n > 0)
{
m = (m * 10) + (n % 10);
n = n / 10;
}
Console.WriteLine(m);
Console.ReadLine();
}
In php $n / 10
will return a float number, not integer.
So $n > 0
will always be true
.
Change while($n > 0)
to while($n > 1)
or while((int)$n > 0)
, then you will get the right result.
PHP is typeless and converts 'on the fly'.
That means, you $n will never be '0' or lower, because $n will be a 'float', when needed.
Try checking for < 1, and you should be fine.
Just to clarify this, $n will behave like this:
$n = 1234 $n = 123.4 $n = 12.34 $n = 1.234 $n = 0.1234 $n = 0.01234 etc.
Meaning: $n will always approach 0, but never reach it. That makes $m infinite, since the loop itself is infinite.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With