存档:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>PHP实现计算器</title> 5 </head> 6 7 <body> 8 <?php 9 $mess = ""; 10 if(isset($_POST["sub"])){ 11 if($_POST["num1"] == ""){ 12 $mess .= "第一个数不能为空!<br>"; 13 } 14 else{ 15 if(!is_numeric($_POST["num1"])){ 16 $mess .="第一个数必须是数字!<br>"; 17 } 18 } 19 20 if($_POST["num2"]==""){ 21 $mess .="第二个数不能为空!<br>"; 22 } 23 else{ 24 if(!is_numeric($_POST["num2"])){ 25 $mess .="第二个数必须是数字!<br>"; 26 } 27 else{ 28 if($_POST["opt"]=="/"&&$_POST["num2"]==0){ 29 $mess .="除数不能为0"; 30 } 31 } 32 } 33 } 34 ?> 35 <table border="1" align="center" width="400"> 36 <form action="" method="post"> 37 <caption><h1>计算器</h1></caption> 38 <tr> 39 <td> 40 <input type="text" size="4" name="num1" value="<?php echo $_POST["num1"]?>" /> 41 </td> 42 43 <td> 44 <select name="opt"> 45 <option value="+" <?php echo $_POST["opt"]=="+" ? "selected" : "" ?>>+</option> 46 <option value="-" <?php echo $_POST["opt"]=="-" ? "selected" : "" ?>>-</option> 47 <option value="x" <?php echo $_POST["opt"]=="x" ? "selected" : "" ?>>x</option> 48 <option value="/" <?php echo $_POST["opt"]=="/" ? "selected" : "" ?>>/</option> 49 <option value="%" <?php echo $_POST["opt"]=="%" ? "selected" : "" ?>>%</option> 50 </select> 51 </td> 52 53 <td> 54 <input type="text" size="4" name="num2" value="<?php echo $_POST["num2"]?>" /> 55 </td> 56 57 <td> 58 <input type="submit" name="sub" value="计算" /> 59 </td> 60 </tr> 61 </form> 62 <?php 63 if(isset($_POST["sub"])){ 64 echo ‘<tr><td colspan="4">‘; 65 if(!$mess){ 66 $sum=0; 67 switch($_POST["opt"]){ 68 case "+": 69 $sum = $_POST["num1"] + $_POST["num2"]; 70 break; 71 case "-": 72 $sum = $_POST["num1"] - $_POST["num2"]; 73 break; 74 case "x": 75 $sum = $_POST["num1"] * $_POST["num2"]; 76 break; 77 case "/": 78 $sum = $_POST["num1"] / $_POST["num2"]; 79 break; 80 case "%": 81 $sum = $_POST["num1"] % $_POST["num2"]; 82 break; 83 } 84 85 echo "结果:{$_POST[‘num1‘]} {$_POST[‘opt‘]} {$_POST[‘num2‘]} = {$sum}"; 86 } 87 else{ 88 echo $mess; 89 } 90 echo ‘</td></tr>‘; 91 } 92 ?> 93 </table> 94 </body> 95 </html>
结果如下:
原文地址:https://www.cnblogs.com/ECJTUACM-873284962/p/8370748.html
时间: 2024-11-08 20:40:39