PHP實現紅包金額拆分演算法案例詳解

來源:互聯網
上載者:User
這次給大家帶來PHP實現紅包金額拆分演算法案例詳解,PHP實現紅包金額拆分演算法的注意事項有哪些,下面就是實戰案例,一起來看一下。

<?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();?>

示範結果:

紅包1=12.36
紅包2=24.37
紅包3=42.71
紅包4=36.92
紅包5=25.84
紅包6=23.17
紅包7=15.92
紅包8=1.35
紅包9=7.75
紅包10=9.61
紅包總金額:200

紅包1=24.59
紅包2=17.66
紅包3=29.67
紅包4=32.34
紅包5=12.67
紅包6=37.15
紅包7=17.41
紅包8=15.23
紅包9=6.13
紅包10=7.15
紅包總金額:200

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

PHP依賴倒置案例詳解

PHP擷取檔案mimes類型步驟詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.