?php
// 新年紅包金額拆分試玩
class CBonus
{
public $bonus;//紅包
public $bonus_num;//紅包個(gè)數(shù)
public $bonus_money;//紅包總金額
public $money_single_max;//單個(gè)紅包限額
public function __construct(){
$this->bonus_num = 10;
$this->bonus_money = 200;
$this->money_single_max = 60;
}
private function randomFloat($min = 0, $max = 1) {
$mt_rand = mt_rand();
$mt_getrandmax = mt_getrandmax();
echo 'mt_rand=' . $mt_rand . ', mt_getrandmax=' . $mt_getrandmax . 'hr/>';
return $min + $mt_rand / $mt_getrandmax * ($max - $min);
}
//計(jì)算
public function compute()
{
$this->bonus = array();
$bonus_money_temp = $this->bonus_money;
$money_single_max = $this->money_single_max;
$i = 1;
while($i $this->bonus_num)
{
if ($money_single_max > $bonus_money_temp)
{
$money_single_max = floatval(sprintf("%01.2f", $bonus_money_temp / 2));//剩余金額不夠分時(shí),把剩余金額的一半作為備用金
}
$bonus_money_rad = $this->randomFloat(0.01, $money_single_max);//一個(gè)紅包隨機(jī)金額 最小的1分錢
$bonus_money_rad = floatval(sprintf("%01.2f", $bonus_money_rad));
$bonus_money_temp = $bonus_money_temp - $bonus_money_rad ;//待分配的總剩余金額
$bonus_money_temp = floatval(sprintf("%01.2f", $bonus_money_temp));
$this->bonus[] = $bonus_money_rad;
//echo $bonus_money_rad . ',' . $bonus_money_temp . 'hr/>';
$i++;
}
$this->bonus[] = $bonus_money_temp;//分配剩余金額給最后一個(gè)紅包
}
//打印
public function output(){
$total = 0;
foreach($this->bonus as $k => $v)
{
echo '紅包' . ($k+1) . '=' . $v . 'br/>';
$total += $v;
}
echo '紅包總金額:'.$total;
}
}
$CBonus = new CBonus();
$CBonus->compute();
$CBonus->output();
?>