找到重复小数的重复部分 - PHP

时间:2013-12-03 04:04:54

标签: php

我使用此代码随机生成重复小数...

do{
    $divisor_array = array(3, 6, 9, 11, 22, 33);
    $divisor = $divisor_array[array_rand($divisor_array)];
    $number = mt_rand(1, 100);

    $decimal_value = $number / $divisor;
} while (strlen($decimal_value) < 5);

echo $number / $divisor;

然后我想在重复部分上显示重复条的数字。

示例:5.83434343434343 ....
将是5.8 <span style="text-decoration: overline;">34</span>

如果随机生成重复小数,有关如何执行此操作的任何想法吗?

1 个答案:

答案 0 :(得分:3)

要说这并不像我想象的那么容易。但我得到了它的工作。我确信有一种更有效的方法可以做到这一点,希望其他人会改进这一点。特别是它被打印的部分。

$number1 =  $number / $divisor;
if(findRepeat( $number1 ) !== false)
{
    $result = findRepeat($number1);
    $leadingNum = strstr($number1, '.', true);
    $nonRepeat = substr($number1, strpos($number1, '.') + 1 , $result['position']);
    if($nonRepeat == '')
        $nonRepeat = '.';

    $repeat = substr($number1,strpos($number1,$nonRepeat) + strlen($nonRepeat), $result['patternSize']);
    $nonRepeat = $nonRepeat == '.' ? '.' : '.'.$nonRepeat;
    echo $leadingNum.$nonRepeat."<span style='text-decoration:overline'>".$repeat."</span>";

}
else
  echo number_format( $number1 , 6);

现在为功能

function findRepeat($number)
{
    $maxLength = 6;
    $decimal = substr($number, strpos($number,'.') + 1 );
    if(strlen($decimal) >= $maxLength )
        $decimal = substr($decimal,0, $maxLength);
    else
        $maxLength = strlen($decimal);

    for($i =0; $i < $maxLength - 3; ++$i)
    {
        //check for single repeition
        if( $decimal[$i] == $decimal[$i + 1] &&  $decimal[$i + 1] == $decimal[$i+2])
            return array('position'=>$i,'patternSize'=>1);
        //triple repetition
        if(substr($decimal,$i,3) == substr($decimal, $i + 3, 3) )
            return array('position'=>$i,'patternSize'=>3);
        //double repetition
        if(substr($decimal,$i,2) == substr($decimal, $i + 2, 2) )
            return array('position'=>$i,'patternSize'=>2);
    }

    return false;
}