Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behavior in PHP - Same code gives correct results in C# and Python

Tags:

python

c#

php

math

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();
}
like image 933
spidEY Avatar asked Sep 06 '12 10:09

spidEY


2 Answers

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.

like image 54
xdazz Avatar answered Oct 24 '22 20:10

xdazz


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.

like image 44
ATaylor Avatar answered Oct 24 '22 20:10

ATaylor