Php递归函数无限循环误差

时间:2018-08-19 12:55:21

标签: php

我正在使用php递归函数来计算最近的销售价格。但我不知道为什么它会无限运行并抛出最大执行错误。

如下所示:

 function getamazonsaleper($portal)
      {
          $cp = floatval($this->input->post('cp')); //user provided inputs
          $sp = floatval($this->input->post('sp')); //user provided input
          $gst = floatval($this->input->post('gst')); //user provided input
          $rfsp = floatval($this->input->post('rfsp')); //user provided input
          $mcp = (int)($this->input->post('mcp')); //user provided input
          $weight = floatval($this->input->post('weight')); //user provided input

          $output = $this->getsalepercent($cp,$sp,$gst,$rfsp,$mcp,$weight,$portal); 
          return $output;




      }
      function getsalepercent($cp,$sp,$gst,$rfsp,$mcp,$weight,$portal) //recursive funtion
      {

          $spcost = ((($sp/100)*$cp));
          $gstamount= (($spcost/(100+$gst))*$gst);
          $rfspamount= ($spcost*($rfsp/100));
          $mcpamount= ($cp*($mcp/100));

          $fixedfee=$this->getfixedfee($portal,$spcost);
          $weightfee=$this->getweightprice($portal,$weight);
          $totalcost=$fixedfee+$weightfee+$rfspamount;
          $gstinput=($totalcost*(18/100));
          $remittances = $spcost-$totalcost-$gstinput;
          $actualprofit= $remittances-$cp-$gstamount+$gstinput;
          $actualprofitpercent = ($actualprofit/$cp)*100;

          if( $actualprofitpercent >= $mcp)
          {
              return $sp;

          }elseif($actualprofitpercent < $mcp)
          {
              $newsp = (int)($sp+10) ;
              $this->getsalepercent($cp,$newsp,$gst,$rfsp,$mcp,$weight,$portal);

          }

      }

有人可以告诉我如何解决此问题吗?预先感谢。

已编辑:

参数

$cp=100;
$sp=200;
$mcp=20;
$weight=0.5;
$gst=28;
$rfsp=6.5;

1 个答案:

答案 0 :(得分:0)

首先要注意的几个事项:
-您使用$ gstinput的方式在计算$ actualprofit时会自行抵消(这是$ remittances中的-$ gstinput,它会加到+ $ gstinput中)。
-$ mcpamount似乎在代码中完全未使用...我想了一秒钟,您可能会在进行比较时就简单地混淆了vars,但是对于$ cp = 100来说毫无区别。

即使如此,当我使用您给出的$ sp = 200(并增长10)的示例值进行一些计算时,我得到:

$ actualprofit的价值,对于$ cp = 100,也是$ actualprofitpercent的价值...

对于$ sp = 200:
43.25-$ fixedfee-$ weightfee

对于$ sp = 210:
50.4125-$ fixedfee-$ weightfee

对于$ sp = 220:
57.575-$ fixedfee-$ weightfee

因此,对于每个$ sp = $ sp + 10递归,$ actualprofitpercent的值(不考虑$ fixedfee和$ weightfee)似乎增加了7.1625。
$ weightfee的值应该保持不变,但是$ fixedfee的值取决于$ sp的值...可能是在每次递归时getfixedfee()返回的值都比7.1625快吗?