【发布时间】: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