PHP中多个数字的比例最简单的方法是什么? [英] What is the simplest way to get a ratio in PHP of multiple numbers?

查看:751
本文介绍了PHP中多个数字的比例最简单的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经根据我在'net ...

中找到的示例对此进行了调整...
$ b $ pre $函数比例$ a ,$ b){
$ _a = $ a;
$ _b = $ b;

while($ _b!= 0){

$ remaining = $ _a%$ _b;
$ _a = $ _b;
$ _b = $余数;
}

$ gcd = abs($ _ a);

回报($ a / $ gcd)。 ':'。 ($ b / $ gcd);

}

回声比(9,3); // 3:1

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



我如何修改这个尽可能多的参数?



谢谢

解决方案

试试这个gcd函数 http://php.net/manual/en/function。 gmp-gcd.php
或者您必须定义一个gcd函数,如

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

while($ _b!= 0){

$ remaining = $ _a%$ _b;
$ _a = $ _b;
$ _b = $余数;
}
返回$ a;
}

然后修改比例函数

 函数比()
{
$ inputs = func_get_args();
$ c = func_num_args();
if($ c <1)
return''; //空输入
if($ c == 1)
return $ inputs [0]; //只有1个输入
$ gcd = gcd($ input [0],$ input [1]); ($ i = 2; $ i <$ c; $ i ++)
$ gcd = gcd($ gcd,$ input [$ i]); //找到gcd的输入
;
$ var = $ input [0] / $ gcd; //为$($ i = 1; $ i< $ c; $ i ++)
$ var。=':'输出
。 ($ input [$ i] / $ gcd); //计算比例
返回$ var;
}


I've adapted this from an example that I found on the 'net...

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

Now I want it to use func_get_args() and return the ratios for multiple numbers. It looks like a recursive problem, and recursion freaks me out (especially when my solutions infinitely loop)!

How would I modify this to take as many parameters as I wanted?

Thanks

解决方案

1st, try this gcd function http://php.net/manual/en/function.gmp-gcd.php Or else you must define a gcd function like

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

        while ($_b != 0) {

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

Then modify the ratio function

    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; 
    }

这篇关于PHP中多个数字的比例最简单的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆