简体   繁体   English

暂时中断条件

[英]Break condition for a while loop

I have a function to calculate best tank size where it should not have any overflow or deficit. 我有一个计算最佳水箱尺寸的功能,该水箱不应有任何溢流或不足。

public static function calculateTankSize($rainfall, $roofArea, $household)
    {

        $demand = $household * 140 * 30;
        $volume = 0;
        $size = 500;
        $status = false;
        while($size < 50000 and $status != true) {
            $waterLevels = array();
            foreach ($rainfall as $amount) {
                $runoffAmount = 0.80 * ($amount - 2) * $roofArea;
                $volume = $volume + ($runoffAmount - $demand);
                if ($volume > $size) {
                    $overflow = $volume - $size;
                    $deficit = 0;
                    $volume = $volume - $overflow;
                } elseif ($volume < 0) {
                    $deficit = abs($volume);
                    $overflow = 0;
                    $volume = 0;
                } else {
                    $overflow = 0;
                    $deficit = 0;
                }
                array_push($waterLevels, array(
                    "volume" => $volume,
                    "overflow" => $overflow,
                    "deficit" => $deficit
                ));
            }
            $status = Rainfall::checkTankStatus($waterLevels);
            $size = $size + 500;
        }
        return $size;
    }

The checkStatus function looks like this: checkStatus函数如下所示:

public static function checkTankStatus($waterLevels)
    {
        $count = 0;
        foreach ($waterLevels  as $value){
            if ($value['overflow'] == 0 && $value['deficit'] == 0){
                $count = $count + 1;
            }
        }
        if ($count == 12){
            return true;
        }
        else
            return false;
    }

I get the output as 50000 which is the end of the loop. 我得到的输出为50000,这是循环的结尾。 The answer is around 35000. The status condition in the while does not fail throughout the loop. 答案大约是35000。while中的状态条件在整个循环中不会失败。 I am stuck with this for a long time now. 我已经坚持了很长时间。 What is the mistake in the function? 函数中有什么错误?

Note: For the test case, I give roof area as 120, household as 1 and rainfall is an array like shown below and should get 35000 注意:对于测试用例,我将屋顶面积设为120,将家庭面积设为1,降雨是一个如下所示的数组,应为35000

[
  0 => 59
  1 => 57
  2 => 54
  3 => 76
  4 => 76
  5 => 87
  6 => 82
  7 => 83
  8 => 88
  9 => 91
  10 => 84
  11 => 74
]

Thanks @Deadooshka. 谢谢@Deadooshka。 I had to rewrite the $volume back to zero after the completion of 'for each' cycle. 在完成“ for each”循环后,我不得不将$ volume重写为零。 Hence, moving the $volume = 0 inside the while loop, did the magic. 因此,在while循环内移动$ volume = 0确实神奇了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM