2017-02-28 68 views
0

我已經做了一個簡單的計算器使用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; 
} 
?> 

回答

0

在devide情況下,你必須檢查$這個 - > b值之前使devide操作:

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

我希望這會幫助你!

+0

如果1號就是0? – DarkSideKillaz

+0

$ this->是0沒有問題,結果將是0 –

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

如果第一個數字是0,該怎麼辦? – DarkSideKillaz

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

您可以使用嘗試捕捉與異常處理

 case 'divide': 
      try { 
       if(!$this->b){ 
        throw new Exception('Division by zero .'); 
       } 
        return $this->a/$this->b; 
      } catch (Exception $e) { 
       return $e->getMessage(); 
      } 
      break;