如何处理除零异常

时间:2017-02-28 03:33:00

标签: php exception-handling divide-by-zero

我使用php制作了一个简单的计算器,我想处理除零除外的异常,我是新手并需要帮助如何做到这一点,如果有人可以提供帮助: - 以下是我的代码

<?php

$result = 0;
class calculator
{
    var $a;
    var $b;
    function checkoperation($operator)
    {
        switch ($operator) {

            case 'divide':
                return $this->a / $this->b;
                break;

            case 'multiply':
                return $this->a * $this->b;
                break;

            case 'add':
                return $this->a + $this->b;
                break;

            case 'subtract':
                return $this->a - $this->b;
                break;
        }
    }
    function getresult($a, $b, $c)
    {
        $this->a = $a;
        $this->b = $b;
        return $this->checkoperation($c);
    }
}
$cal = new calculator();
if (isset($_POST['calculate_btn'])) {
    $first_num  = $_POST['first_num_txtbox'];
    $second_num = $_POST['second_num_txtbox'];
    $operation  = $_POST['operation_slctbox'];
    $result     = $cal->getresult($first_num, $second_num, $operation);
    echo "The result is: " . $result;
}
?>

4 个答案:

答案 0 :(得分:0)

在dide情况下,您必须在make devide运算符之前检查$ this-&gt; b值:

case 'divide':
    return ($this->b == 0) ? 'Infinitive' : $this->a / $this->b;
    break;

我希望这会对你有所帮助!

答案 1 :(得分:0)

将if语句放在最后。我的意思是:

if ($second_num==0)
{echo "<h1>ERROR:CANT BE DIVIDED</h1>"}
else
{$result = $cal->getresult($first_num, $second_num, $operation);
echo "The result is: " . $result;}

答案 2 :(得分:0)

在检查后这是一个选项,这只是一个选项,它会检查这两个数字不是0

if(isset($_POST['calculate_btn']))
{   
    if($_POST['operation_slctbox'] == "divide")
    {
        if($_POST['first_num_txtbox'] !== "0" || $_POST['second_num_txtbox'] !== "0")
        {
            //do code if either are 0 and divide is selected or return with error cannot divide by 0
        }
        else
        {
           $result = $cal->getresult($first_num, $second_num, $operation);
        }
    }
    else
    {
         $result = $cal->getresult($first_num, $second_num, $operation);
    }
    echo "The result is: " . $result;
}

答案 3 :(得分:0)

您可以使用带有异常处理的try catch

    var isChecked= document.getElementById("btnSelect").checked;
    if(isChecked){
       // write your code here
}