2017-02-28 4 views
0

私はPHPを使って簡単な電卓を作っていますが、私は除算の例外をゼロで扱いたいと思います。私はこれで初めてで、誰かが助けることができるなら、これを行う方法を手助けします: - 以下はdevide場合ゼロ除算の処理方法

<?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

私のコードは、あなたがチェックする必要があります$ this->作る前に、b値devide演算子:

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

私は、これはあなたを助けることを願っています!

+0

数1が0何である場合を例外処理でのtryキャッチを使用することができますか? – DarkSideKillaz

+0

$ this-> aは0で問題はありません。結果は0になります –

0

最後にput 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

YOUは

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