小于运算符在 PHP 中无法正常工作,而循环

我正在尝试根据每个积分的金额进行一些计算,以获得所请求金额中使用的总积分。


请参考以下代码:


<?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

$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.50


上面的场景输出,但我相信它应该只是.在迭代的点,并且 已经具有相同的值。为什么 while 循环仍然满足比较变量的两个值不小于但等于?5.505.005.00$total_amount$request_amount3114.55


料青山看我应如是
浏览 140回答 4
4回答

一只萌萌小番薯

您正在比较浮点数。尝试使用while&nbsp;(bccomp($total_amount,&nbsp;$request_amount)&nbsp;===&nbsp;-1)&nbsp;{

慕神8447489

使用小数分数作为浮点数进行计算时会发生错误。浮点数不能精确表示某些十进制数。仅使用 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);//outputvar_dump($points);&nbsp; //string(3) "5.0"

德玛西亚99

<?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 POINTSwhile($total_amount < $request_amount){&nbsp; &nbsp; $points=$new_points;&nbsp; &nbsp; $new_points = $new_points+0.50; //POINTS INCREMENTING BY 0.5&nbsp; &nbsp; $total_amount = $new_points * $amount_perpoints;}echo $points;?>

侃侃无极

我认为@jeff是对的:&nbsp;$amount_perpoints = bcdiv(622.9106666666667,1,2); // AMOUNT OF MONEY PER POINTS&nbsp; &nbsp; $request_amount = 3114.55; //REQUESTED AMOUNT OF POINTS&nbsp; &nbsp; $points = 0; // THIS WILL CONTAIN THE TOTAL POINTS&nbsp; &nbsp; $total_amount = 0; // THIS WILL INCREMENT ACCORDING TO THE PRODUCT OF THE CURRENT POINT AND AMOUNT PER POINTS&nbsp; &nbsp; while($total_amount <= $request_amount){&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $points = $points+0.50; //POINTS INCREMENTING BY 0.5&nbsp; &nbsp; &nbsp; &nbsp; $total_amount = $points * $amount_perpoints;&nbsp; &nbsp; }&nbsp; &nbsp; echo $points;由于你数到它达到期望的点,它的灵魂是少或等于。它给出的输出为 : 5.5
打开App,查看更多内容
随时随地看视频慕课网APP