4 回答

TA貢獻1780條經驗 獲得超1個贊
使用小數分數作為浮點數進行計算時會發生錯誤。浮點數不能精確表示某些十進制數。僅使用 BC 數學函數進行此類計算。您也不需要循環。
$amount_perpoints = "622.91"; // AMOUNT OF MONEY PER POINTS
$request_amount = "3114.55"; //REQUESTED AMOUNT OF POINTS for result 5.0
//$request_amount = "3426.005"; //REQUESTED AMOUNT OF POINTS for result 5.5
$point_step = "0.50";
//calculation
$points = bcdiv($request_amount,$point_step,2);
$points = bcdiv($points,$amount_perpoints,0);
$points = bcmul($points,$point_step,1);
//output
var_dump($points); //string(3) "5.0"

TA貢獻1770條經驗 獲得超3個贊
<?php
$amount_perpoints = bcdiv(622.9106666666667,1,2); // AMOUNT OF MONEY PER POINTS
$request_amount = 3114.55; //REQUESTED AMOUNT OF POINTS
$points = 0; // THIS WILL CONTAIN THE TOTAL POINTS
$new_points=0;
$total_amount = 0; // THIS WILL INCREMENT ACCORDING TO THE PRODUCT OF THE CURRENT POINT AND AMOUNT PER POINTS
while($total_amount < $request_amount){
$points=$new_points;
$new_points = $new_points+0.50; //POINTS INCREMENTING BY 0.5
$total_amount = $new_points * $amount_perpoints;
}
echo $points;
?>

TA貢獻2051條經驗 獲得超10個贊
我認為@jeff是對的:
$amount_perpoints = bcdiv(622.9106666666667,1,2); // AMOUNT OF MONEY PER POINTS
$request_amount = 3114.55; //REQUESTED AMOUNT OF POINTS
$points = 0; // THIS WILL CONTAIN THE TOTAL POINTS
$total_amount = 0; // THIS WILL INCREMENT ACCORDING TO THE PRODUCT OF THE CURRENT POINT AND AMOUNT PER POINTS
while($total_amount <= $request_amount){
$points = $points+0.50; //POINTS INCREMENTING BY 0.5
$total_amount = $points * $amount_perpoints;
}
echo $points;
由于你數到它達到期望的點,它的靈魂是少或等于。它給出的輸出為 : 5.5
- 4 回答
- 0 關注
- 169 瀏覽
添加回答
舉報