【问题标题】:Validation for a Divide by Zero in PHP在 PHP 中验证除以零
【发布时间】:2020-10-26 12:16:07
【问题描述】:

我正在用 PHP 制作一个简单的计算器,并希望创建除以 0 的验证。

在用户被零除的那一刻,PHP 发出警告 Warning: Division by zero in

我知道如果用户进行除法,我需要检查 y == 0,但我不确定将它放在我的代码中的哪个位置。

<html>
    <head>
      <title>PHP Calculator</title>
   </head>

   <body>

      <h3>PHP Calculator (Version 6)</h3>
      <p>Add, subtract, divide or multiply and output the result</p>
     
       <form method="get" action="<?php print $_SERVER['PHP_SELF']; ?>">
            <input type = "number" name = "x" placeholder = "0" required>
            <select name = "operator">
                <option>None</option>
                <option>+</option>
                <option>-</option>
                <option>*</option>
                <option>/</option>
            </select>
            <input type = "number" name = "y" placeholder = "0" required>
            
            <input type="submit" name="submit" value="Calculate"/>
        </form>
       
        <p>The answer is: </p>
       
    <?php 
       if (isset($_GET['submit'])) {
           $x = $_GET['x'];
           $y = $_GET['y'];
           $operator = $_GET['operator'];
           
      
       switch ($operator) {
           case "+":
               echo $x + $y;
               break;
           case "-":
               echo $x - $y;
               break;
           case "*":
               echo $x * $y;
               break;
           case "/":
               echo $x / $y;
               break;
           default:
               echo "You should to select a method!";
               break;
       }

     }
  
    ?>    
    </body>
</html>

【问题讨论】:

  • 把它放在我认为的case "/": 区域可能有意义吗?

标签: php html validation calculator


【解决方案1】:

我会把它放在除法情况下的 switch 语句中,

 case "/":
           echo $y==0 ? 'Illegal divisor' : ($x / $y);
           break;

这将确保您的代码的可读性。

如果您不熟悉三元运算符,请参考以下语法:

{条件} ? {真陈述}:{假陈述}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多