简体   繁体   中英

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:

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. The answer is around 35000. The status condition in the while does not fail throughout the loop. 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

[
  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. I had to rewrite the $volume back to zero after the completion of 'for each' cycle. Hence, moving the $volume = 0 inside the while loop, did the magic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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