欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php获取指定范围内最接近数的方法

程序员文章站 2023-08-12 13:58:50
本文实例讲述了php获取指定范围内最接近数的方法。分享给大家供大家参考。具体实现方法如下: // returns the next higher or lower...

本文实例讲述了php获取指定范围内最接近数的方法。分享给大家供大家参考。具体实现方法如下:

// returns the next higher or lower number
function nextrelatednumber($number, $range){  
  $r = $number % $range;
  $f = $number - $r;
  $b = round($r / $range, 0);
  return ($b == 1) ? $f + $range : $f;  
}
// returns the next higher number
function nexthighernumber($number, $range){  
  $r = $number % $range;
  $f = $number - $r;
  $b = ceil($r / $range);
  return ($b == 1) ? $f + $range : $f;  
}
// returns the next lower number
function nextlowernumber($number, $range){  
  $r = $number % $range;
  $f = $number - $r;
  $b = floor($r / $range);
  return ($b == 1) ? $f + $range : $f;  
}
// returns the next related number from an array
function nextnumberarray($number, $numberrangearray){
  $w = 0;
  $c = -1;
  $abstand = 0;
  $l = count($numberrangearray);    
  for($pos=0; $pos < $l; $pos++){
    $n = $numberrangearray[$pos];
    $abstand = ($n < $number) ? $number - $n : $n - $number;
    if ($c == -1){
      $c = $abstand;
      continue;
    }
    else if ($abstand < $c){
      $c = $abstand;
      $w = $pos;
    }
  }
  return $numberrangearray[$w];
}
 
// examples
// --------
// 0 10 20 30 40 50 ...
print 'nextrelatednumber: ';
print nextrelatednumber(44, 10) . "\n";
// returns --> 40
// 0 20 40 60 80 100 ...
print 'nexthighernumber: ';
print nexthighernumber(41, 20) . "\n";
// returns --> 60
// 0 5 10 15 20 25 30 35 ...
print 'nextlowernumber: ';
print nextlowernumber(57, 5) . "\n";
// returns --> 55
// example with array
print 'nextnumberarray: ';
print nextnumberarray(45, array(3, 8, 19, 34, 56, 89)) . "\n";
// returns --> 34
// (45 is between 34 and 56 but 34 is the next)

希望本文所述对大家的php程序设计有所帮助。