1 <!--简单的计算器-->
2 <!DOCTYPE html>
3 <html>
4 <head>
5 <title>PHP实现简单计算器</title>
6 <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
7 </head>
8 <?php
9 $num1=true;
10 $num2=true;
11 $numa=true;
12 $numb=true;
13 $message="";
14
15 //单路分支
16 if(isset($_GET["sub"])){
17 if($_GET["num1"]==""){
18 $num1=false;
19 $message.="第一个数不能为空";
20 }
21
22 if(!is_numeric($_GET["num1"])){
23 $numa=false;
24 $message.="第一个数不是数字";
25 }
26
27 if($_GET["num2"]==""){
28 $num2=false;
29 $message.="第二个值不能为空";
30 }
31
32 if(!is_numeric($_GET["num2"])){
33 $numb=false;
34 $message.="第二个数不是数字";
35 }
36 //判断不能为空,判断为数字
37 if($num1 && $num2 && $numa && numb){
38
39 $sum=0;
40 //多路分支的switch
41 switch ($_GET["ysf"])
42 {
43 case '+':
44 $sum=$_GET["num1"]+$_GET["num2"];
45 break;
46 case '-':
47 $sum=$_GET["num1"]-$_GET["num2"];
48 break;
49 case 'x':
50 $sum=$_GET["num1"]*$_GET["num2"];
51 break;
52 case '/':
53 $sum=$_GET["num1"]/$_GET["num2"];
54 break;
55 case '%':
56 $sum=$_GET["num1"]%$_GET["num2"];
57 break;
58 }
59 }
60 }
61 ?>
62 <body>
63 <table align="center" width="500">
64 <caption><h1>计算器</h1></caption>
65 <form action="jsq.php">
66 <tr>
67 <td>
68 <input type="text" size="5" name="num1" value="<?php echo $_GET["num1"]; ?>">
69 </td>
70 <td>
71 <select name="ysf">
72 <option value="+" <?php if($_GET["ysf"]=="+") echo "selected"; ?>>+</option>
73 <option value="-" <?php if($_GET["ysf"]=="-") echo "selected"; ?>>-</option>
74 <option value="x" <?php if($_GET["ysf"]=="x") echo "selected"; ?>>x</option>
75 <option value="/" <?php if($_GET["ysf"]=="/") echo "selected"; ?>>/</option>
76 <option value="%" <?php if($_GET["ysf"]=="%") echo "selected"; ?>>%</option>
77 </select>
78 </td>
79 <td>
80 <input type="text" size="5" name="num2" value="<?php echo $_GET["num2"]; ?>">
81 </td>
82 <td>
83 <input type="submit" name="sub" value="计算">
84 </td>
85 </tr>
86
87 <?php
88 if(isset($_GET["sub"])){
89 echo '<tr><td colspan="5">';
90 if($num1 && $num2 && $numa && $numb){
91 echo "结果:".$_GET["num1"]."".$_GET["ysf"]."".$_GET["num2"]."=".$sum;
92 }else{
93 echo "$message";
94 }
95 echo '</td></tr>';
96 }
97 ?>
98 </form>
99 </table>
100 </body>
101 </html>