本文介紹了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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選