被零除

时间:2012-10-16 09:40:14

标签: php divide-by-zero

我正在使用一种方法来计算一些分数。这是以下方法:

public function getIntScore($name, $int){
    switch ($name) {
        case "bedrooms":
            $maxscore = 15;
            break;
        case "living_size":
            $maxscore = 10;
            break;
        case "property_size":
            $maxscore = 10;
            break;
        case "date_of_construction":
            $maxscore = 3;
            break;
    }
    $houseattribute = (int) $this->$name;
    $difference = abs($houseattribute - $int);
    if ($difference == 0) {
        return $maxscore;
    }
    $score = ($difference / $houseattribute) * $maxscore;
    return round($score);
}

然而,这给了我一个“除零”错误。我在计算之前检查了变量的值,但没有一个是零。

var_dump($difference, $houseattribute, $maxscore) 

输出:

int(2) int(3) int(15) 

2 个答案:

答案 0 :(得分:1)

确保测试空值:

$houseattribute = (int) $this->$name;
if (empty($houseattribute)) {
   throw new Exception('House attribute is zero.');
}

答案 1 :(得分:0)

解决。我愚蠢到忘记我在数组中循环,第一个$houseattribute3。我的数组中有一个$houseattribute0的项目,但因为在转储变量之后我使用exit;我并不知道它是。我将它改为正整数而不是它正在工作。

相关问题