拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 php获取最接近1的值

php获取最接近1的值

白鹭 - 2022-02-23 2093 0 0
$result_id[][] = "";
$result_total[][] = "";
foreach ($user as $key) {
    $a = 0;
    foreach ($drama as $row) {
        if ($w_average[$key['userid']][$row['id']] > 0) {
            if ($w_average[$key['userid']][$row['id']] < 1) {
                $result_id[$key['userid']][$a] = $row['id'];
                $result_total[$key['userid']][$a] = $w_average[$key['userid']][$row['id']];
                $a  ;
            }
        }
    }
}

我想得到 w_average 的正值和最接近 1 的值。

w_average 是 0.25 和 0.33 但我的源代码的输出是 0.25

如何解决?谢谢

uj5u.com热心网友回复:

您确定该值是作为数字传递的,而不是作为字符串传递的吗?

$w_average = [0.25, 0.33, 1.21, -0.4];
foreach ($w_average as $row) {
    if($row < 1 && $row > 0 ) {
        echo "W_average = ".$row." -> Ok";
    } else {
        echo "W_average = ".$row." -> NO";
    }
}

输出:
W_average = 0.25 -> Ok
W_average = 0.33 -> Ok
W_average = 1.21 -> NO
W_average = -0.4 -> NO

例子:

$w_average = [0.25, 0.33, 1.21, -0.4];
$near = 0; 
foreach ($w_average as $row) {
   if($row < 1 && $row > $near) {
       $near = $row;
   } 
}
echo $near;

输出:0.33

uj5u.com热心网友回复:

您可以使用abs($number - $nearest)来获取值与您想要的数字的距离

function closest(array $numbers, $nearest = 1) {
  $max = PHP_INT_MAX;
  foreach($numbers as $number) {
    $distance = abs($number - $nearest);
    if($distance < $max) {
      $max = $distance;
      $nearest = $number;
    }
  }
  return $nearest;
}

var_dump(closest([0.25, 0.33]));

// Result 0.33
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *