Hướng dẫn find median php
Ngày đăng:
19/09/2022
Trả lời:
0
Lượt xem:
81
$test = array(
array(5,2,1,3,4),
array(),
array(1)
);
foreach($test as $arr){
$count = count($arr);
sort($arr);
$mid = floor(($count-1)/2);
$avg = ($arr)?array_sum($arr)/$count:0;
$median = ($arr)?($arr[$mid]+$arr[$mid+1-$count%2])/2:0;
echo 'avg: '.$avg."
function median($arr){
if($arr){
$count = count($arr);
sort($arr);
$mid = floor(($count-1)/2);
return ($arr[$mid]+$arr[$mid+1-$count%2])/2;
}
return 0;
}
function average($arr){
return ($arr) ? array_sum($arr)/count($arr) : 0;
}
$test = array(
array(5,2,1,3,4),
array(5,4,2,3,1,6),
array(),
array(1),
array(2,4),
);
foreach($test as $arr){
echo 'avg: '.average($arr)." Be careful about how you write your Build an array of the random numbers, then sort them. Then determine if you have a central entry (odd array length) or if you need to average the middle two entries (even array length). Here is a modern implementation of a median method posted in 2022 on CodeReview. Code: (Demo)
Possible Output:
After sorting, elements If you want a
short, inflexible, hardcoded snippet, then you can use |