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

时间:2021-05-26

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

// Returns the next higher or lower numberfunction NextRelatedNumber($number, $range){ $r = $number % $range; $f = $number - $r; $b = round($r / $range, 0); return ($b == 1) ? $f + $range : $f; }// Returns the next higher numberfunction NextHigherNumber($number, $range){ $r = $number % $range; $f = $number - $r; $b = ceil($r / $range); return ($b == 1) ? $f + $range : $f; }// Returns the next lower numberfunction 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 arrayfunction 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 Arrayprint '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程序设计有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章