除以零错误

3

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

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) 

1
你在 $score = ($difference / $houseattribute) * $maxscore; 之前进行了检查吗? 你确定在这一行中除以零会抛出异常吗? - neworld
是的,在那一行之前我检查过了。Yii在第878行给了我一个错误,这一行是$score = ($difference / $houseattribute) * $maxscore; - Sietse
@neworld 这个代码可以正常运行且没有错误。这是奇怪的行为,因为 $houseattribute 不等于 0。 @Narretz 在这个例子中,$this->$name 返回字符串 "3",将其转换为整数会得到 3。 - Sietse
我非常确定问题出在这一行 $houseattribute = (int) $this->$name;。可能的值是什么?你期望它输出什么值? - Brett Gregson
根据您的评论,您不需要将字符串转换为整数($houseattribute =(int)$this-> $name)。您说$this-> $name的值为“3”。在PHP中,3 ==“3”,例如:if(3 ==“3”){die(“yes”);}三个等号比较类型(===)。因此,(int)是不必要的。不知道是否能解决问题。 - Brett Gregson
显示剩余3条评论
2个回答

1

请确保测试空值:

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

将您的代码添加后会出现给定的异常。然而,我不理解这个问题。如果我使用 echo $houseattribute; 或者 var_dump($houseattribute); 分别会得到 3 或者 int(3) 的结果。为什么 empty() 函数会返回 true 呢? - Sietse
可能会有一些看不见的字符在开头,而且转换失败是因为第一个字符不是数字。尝试逐个输出变量中的字符。 - Pentium10
很抱歉,没有看不见的字符。我使用了 substr($houseattribute, 0, 1); 来获取第一个字符,结果是 3。然后,我通过使用 var_dump($houseattribute, (int)$houseattribute); 检查是否正确执行了转换。结果是 string(1) "3" int(3) - Sietse
很抱歉,这是 PHP 的一个 bug。请尝试在其他文件中创建一些简单的示例:$a = (int)'3home' .... 或者尝试更改 PHP 版本。 - neworld

0
解决了。我很蠢,忘记了我正在遍历一个数组,在那里第一个$houseattribute3。我的数组中有一个项目,其中$houseattribute0,但由于在转储变量后我使用了exit;,所以我不知道它是什么。我将其更改为正整数,现在它可以工作了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接