为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
料青山看我应如是 2022-09-17 21:55:36
我正在尝试根据每个积分的金额进行一些计算,以获得所请求金额中使用的总积分。请参考以下代码:<?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 POINTSwhile($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
查看完整描述

4 回答

?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

您正在比较浮点数。尝试使用

while (bccomp($total_amount, $request_amount) === -1) {


查看完整回答
反对 回复 2022-09-17
?
慕神8447489

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"


查看完整回答
反对 回复 2022-09-17
?
德玛西亚99

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;


?>


查看完整回答
反对 回复 2022-09-17
?
侃侃无极

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


查看完整回答
反对 回复 2022-09-17
  • 4 回答
  • 0 关注
  • 139 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信