实现一个简单的计算器功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>计算器</title>
<style>
body{
background-color: #ccc;
}
h3{
color: lightseagreen;
}
</style>
</head>
<body>
<h3>计算器</h3>
<form action="" method="post">
<!-- !第一个数字 -->
<input type="number" name="number1" value="<?= isset($_POST['number1']) ? $_POST['number1'] : '' ?>">
<select name="opt" id="">
<option value="1" <?php echo isset($_POST['opt']) && $_POST['opt'] == '1' ? 'selected' : '' ?>>+</option>
<option value="2" <?php echo isset($_POST['opt']) && $_POST['opt'] == '2' ? 'selected' : '' ?>>-</option>
<option value="3" <?php echo isset($_POST['opt']) && $_POST['opt'] == '3' ? 'selected' : '' ?>>*</option>
<option value="4" <?php echo isset($_POST['opt']) && $_POST['opt'] == '4' ? 'selected' : '' ?>>/</option>
<option value="5" <?php echo isset($_POST['opt']) && $_POST['opt'] == '5' ? 'selected' : '' ?>>%</option>
</select>
<input type="number" name="number2" value="<?php echo isset($_POST['number2']) ?>">
<input type="submit" name="sub" value="计算">
</form>
</body>
</html>
<?php
// echo $_POST['number1'];
$error = '';
if(($_POST['opt'] == 4 || $_POST['opt'] == 5) && $_POST['num2'] === 0)
{
$error .= '除法运算的时候,第二个值不能为0';
}elseif(empty($_POST['number1']))
{
$error .= '请输入第一个数!!!';
}elseif(empty($_POST['number2'])){
$error .= '请输入第二个数!!!!';
}
if(isset($_POST['sub'])){
if(empty($error)){
switch($_POST['opt'])
{
case $_POST['opt'] == 1:
$answer = $_POST['number1'] + $_POST['number2'];
break;
case $_POST['opt'] == 2:
$answer = $_POST['number1'] - $_POST['number2'];
break;
case $_POST['opt'] == 3:
$answer = $_POST['number1'] * $_POST['number2'];
break;
case $_POST['opt'] == 4:
$answer = $_POST['number1'] / $_POST['number2'];
break;
case $_POST['opt'] == 5:
$answer = $_POST['number1'] % $_POST['number2'];
break;
}
echo '您的答案:'.$answer;
}else{
echo $error;
}
}