Как обрабатывать деление на ноль исключений

Я сделал простой калькулятор с использованием 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

Решение

В другом случае вы должны проверить значение $ this-> b перед оператором make devide:

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

Я надеюсь, что это поможет вам!

0

Другие решения

поставить заявление в конце. Я имею в виду :

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,

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

ВЫ можете использовать try catch с обработкой исключений

       case 'divide':
try {
if(!$this->b){
throw new Exception('Division by zero .');
}
return $this->a / $this->b;
} catch (Exception $e) {
return $e->getMessage();
}
break;
0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector