【问题标题】:Division By Zero被零除
【发布时间】:2012-10-16 09:40:13
【问题描述】:

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

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) 

【问题讨论】:

  • 您在$score = ($difference / $houseattribute) * $maxscore; 之前检查过吗?你完全确定在这条线上除以零吗?
  • 是的,我在该行之前检查了它。 Yii 在第 878 行给了我一个错误,即$score = ($difference / $houseattribute) * $maxscore; 所在的行。
  • 你能试试$score = ($difference / ($houseattribute + 1)) * $maxscore;吗?
  • 你想用$houseattribute = (int) $name; 完成什么这会将字符串转换为整数,结果为0。
  • @neworld 这有效并且不会导致错误。这是一种奇怪的行为,因为 $houseattribute 不是 0。@Narretz $this->$name 在此示例中返回字符串“3”,将其转换为 int 会给我 3。

标签: php divide-by-zero


【解决方案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?
  • 开头可能有一些看不见的字符,并且转换无法将字符串解码为数字,因为它遇到的第一个字符不是数字。尝试逐字符回显变量 char。
  • 恐怕没有看不见的字符。我使用substr($houseattribute, 0, 1); 来获取第一个字符,结果是3。然后,我使用var_dump($houseattribute, (int)$houseattribute); 检查了演员阵容是否正确执行。这导致了string(1) "3" int(3)。
  • 恐怕这是一个 PHP 错误。尝试在其他文件中做一些简单的例子:$a = (int)'3home' .... 或者尝试更改 PHP 版本
【解决方案2】:

解决了。我傻到忘记了我正在遍历一个数组,其中第一个$houseattribute 是3。我的数组中有一个项目,其中$houseattribute 是0,但是因为我在转储变量后使用了exit;,所以我不知道它是。我将其更改为正整数,但它不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多