?php
// 新年红包金额拆分试玩
class CBonus
{
  public $bonus;//红包
  public $bonus_num;//红包个数
  public $bonus_money;//红包总金额
  public $money_single_max;//单个红包限额
  
  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);
  }
  //计算
  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));//剩余金额不够分时,把剩余金额的一半作为备用金
      }
      $bonus_money_rad = $this->randomFloat(0.01, $money_single_max);//一个红包随机金额 最小的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;//分配剩余金额给最后一个红包
  }
  //打印
  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();
?>