用PHP计算数组的中位数

时间:2018-09-20 23:11:16

标签: php arrays median

我正在尝试弄清楚如何计算随机生成的数字数组的中位数。我已经设置好所有数组,但是在组合函数进行计算时遇到了麻烦。

这是我到目前为止所拥有的:

//array 
$lessFifty = array();
$moreFifty = array();

//number generation
for ($i = 0; $i<=30; $i++) {
      $number = rand(0, 100);

//Sorting <50>      
if ($number < 50 ) {
    $lessFifty[] = $number;
} else {
    $moreFifty[] = $number; 
   } 
}
 echo print_r($lessFifty); 
 echo "<br>" ;
 echo print_r($moreFifty);

   //Average
echo "<p> Average of values less than fifty: </p>";
    print   array_sum($lessFifty) / count($lessFifty) ;
echo "<p> Average of values greater than fifty: </p>" ;  
    print   array_sum($moreFifty) / count($moreFifty) ;

//Median
$func = function (median ($array, $output = $median)){ 
    if(!is_array($array)){
        return FALSE;
    }else{
        switch($output){
                rsort($array);
                $middle = round(count($array) 2);
    $total = $array[$middle-1];
        break; 
    return $total;
    }
}

echo $func ; 

我很确定我在做中间部分完全错误。我只是在学习,事实证明这是一个挑战。

1 个答案:

答案 0 :(得分:1)

请注意如何编写<Flexbox flexDirection="column"> <Flexbox element="header" height="60px"> <div style={{ flexGrow: 0}}> <img src={Logo} /> </div> <div style={{flexGrow: 8}}> <SearchBar onChange={() => console.log('onChange')} onRequestSearch={() => console.log('onRequestSearch')} style={{ margin: '0 auto', maxWidth: 800 }} /> </div> <div> <Button>Become a host</Button> </div> <div> <Button>Sign up</Button> </div> <div> <Button>Log in</Button> </div> </Flexbox> </Flexbox> 循环。如果要输入30条,则不应使用for(),否则将以31结尾,因为<=以0开头。

构建一个随机数数组,然后对其进行排序。

然后确定您是否有中央条目(奇数数组长度),或者是否需要平均中间两个条目(甚至数组长度)。

代码:(Demo

$i

可能的输出:

$limit = 30;  // how many random numbers do you want?  30 or 31?
for ($i = 0; $i < $limit; ++$i) {
    $numbers[] = rand(0, 100);
}
var_export($numbers);

//echo "\n---\nAverage: " , array_sum($numbers) / $limit;
echo "\n---\n";

sort($numbers);
$count = sizeof($numbers);   // cache the count
$index = floor($count/2);  // cache the index
if (!$count) {
    echo "no values";
} elseif ($count & 1) {    // count is odd
    echo $numbers[$index];
} else {                   // count is even
    echo ($numbers[$index-1] + $numbers[$index]) / 2;
}

排序后,元素array ( 0 => 27, 1 => 24, 2 => 84, 3 => 43, 4 => 8, 5 => 51, 6 => 60, 7 => 86, 8 => 9, 9 => 48, 10 => 67, 11 => 20, 12 => 44, 13 => 85, 14 => 6, 15 => 63, 16 => 41, 17 => 32, 18 => 64, 19 => 73, 20 => 43, 21 => 24, 22 => 15, 23 => 19, 24 => 9, 25 => 93, 26 => 88, 27 => 77, 28 => 11, 29 => 54, ) --- 43.5 [14]分别持有[15]43。这些“中间两个”值的平均值是确定结果的方式。 (Hardcoded numbers demo


如果您想要一个简短,固定,硬编码的代码段,则可以使用443014作为您的预定大小和索引。

15