中断循环的中断条件

时间:2017-04-22 03:56:51

标签: php laravel loops

我有一个计算最佳油箱尺寸的功能,它不应有任何溢出或缺陷。

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;
    }

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;
    }

我得到输出为50000,这是循环的结束。答案是35000左右。在整个循环中,while中的状态条件不会失败。我现在已经坚持了很久。这个函数有什么错误?

注意:对于测试用例,我给出屋顶面积为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
]

1 个答案:

答案 0 :(得分:0)

谢谢@Deadooshka。在'for each'循环完成后,我不得不将$ volume重写为零。因此,在while循环中移动$ volume = 0就行了神奇。