在PHP中获得多个数字的比率的最简单方法是什么?

ale*_*lex 3 php math recursion function

我从一个我在'网上发现的例子中改编了这个...

function ratio($a, $b) {
    $_a = $a;
    $_b = $b;

    while ($_b != 0) {

        $remainder = $_a % $_b;
        $_a = $_b;
        $_b = $remainder;   
    }

    $gcd = abs($_a);

    return ($a / $gcd)  . ':' . ($b / $gcd);

}

echo ratio(9, 3); // 3:1
Run Code Online (Sandbox Code Playgroud)

现在我希望它使用func_get_args()并返回多个数字的比率.它看起来像一个递归问题,并且递归使我感到厌烦(特别是当我的解决方案无限循环时)!

我如何修改它以获取尽可能多的参数?

谢谢

Ban*_*Dao 5

1,尝试这个gcd函数http://php.net/manual/en/function.gmp-gcd.php 否则你必须定义一个gcd函数

    function gcd($a, $b) {
        $_a = abs($a);
        $_b = abs($b);

        while ($_b != 0) {

            $remainder = $_a % $_b;
            $_a = $_b;
            $_b = $remainder;   
        }
        return $a;
    }
Run Code Online (Sandbox Code Playgroud)

然后修改比率函数

    function ratio()
    {
        $inputs = func_get_args();
        $c = func_num_args();
        if($c < 1)
            return ''; //empty input
        if($c == 1)
            return $inputs[0]; //only 1 input
        $gcd = gcd($input[0], $input[1]); //find gcd of inputs
        for($i = 2; $i < $c; $i++) 
            $gcd = gcd($gcd, $input[$i]);
        $var = $input[0] / $gcd; //init output
        for($i = 1; $i < $c; $i++)
            $var .= ':' . ($input[$i] / $gcd); //calc ratio
        return $var; 
    }
Run Code Online (Sandbox Code Playgroud)