本文实例讲述了php编程实现简单的网页版计算器功能。分享给大家供大家参考,具体如下:
如何通过php代码来实现一个网页版的计算器的简单功能?下面就是通过php基础知识来做的网页版计算器,功能只有“加减剩除求余”,其他的一些计算功能可扩展。
实现简单计算器的具体php代码如下(这是php文件jsq.php的全部代码):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
<html>
<head>
<title>这是一个网页版的简单计算器</title>
<meta http-equiv= "content-type" content= "text/html;chaset=utf-8" >
</head>
<?php
$num1 =true;
$num2 =true;
$numa =true;
$numb =true;
$message = "" ;
if (isset( $_get [ "sub" ])){
if ( $_get [ "num1" ]== "" ){
$num1 =false;
$message .= "第一个数不能为空" ;
}
if ( $_get [ "num2" ]== "" ){
$num1 =false;
$message .= "第二个数不能为空" ;
}
if (! is_numeric ( $_get [ "num1" ])){
$numa =false;
$message .= "第一个数应该是数字" ;
}
if (! is_numeric ( $_get [ "num2" ])){
$numb =false;
$message .= "第二个数应该是数字" ;
}
if ( $num1 && $num2 && $numa && $numb ){
$sum =0;
switch ( $_get [ "ysf" ]){
case "+" :
$sum = $_get [ "num1" ]+ $_get [ "num2" ];
break ;
case "-" :
$sum = $_get [ "num1" ]- $_get [ "num2" ];
break ;
case "x" :
$sum = $_get [ "num1" ]* $_get [ "num2" ];
break ;
case "/" :
$sum = $_get [ "num1" ]/ $_get [ "num2" ];
break ;
case "%" :
$sum = $_get [ "num1" ]% $_get [ "num2" ];
break ;
}
}
}
?>
<body>
<table align= "center" border= "1" width= "500" >
<caption><h1>网页计算器</h1></caption>
<form action= "jsq.php" >
<tr>
<td>
<input type= "text" size= "5" name= "num1" value= "<?php echo $_get[" num1 "] ?>" >
</td>
<td>
<select name= "ysf" >
<option value= "+" <?php if ( $_get [ "ysf" ]== "+" ) echo "selected" ?>>+</option>
<option value= "-" <?php if ( $_get [ "ysf" ]== "-" ) echo "selected" ?>>-</option>
<option value= "x" <?php echo $_get [ "ysf" ]== "x" ? "selected" : "" ?>>x</option>
<option value= "/" <?php echo $_get [ "ysf" ]== "/" ? "selected" : "" ?>>/</option>
<option value= "%" <?php echo $_get [ "ysf" ]== "%" ? "selected" : "" ?>>%</option>
</select>
</td>
<td>
<input type= "text" size= "5" name= "num2" value= "<?php echo $_get[" num2 "] ?>" >
</td>
<td>
<input type= "submit" name= "sub" value= "计算" >
</td>
<?php
if (isset( $_get [ "sub" ])){
echo '<tr><td colspan="4">' ;
if ( $num1 && $num2 && $numa && $numb ){
echo "结果:" . $_get [ "num1" ]. " " . $_get [ "ysf" ]. " " . $_get [ "num2" ]. " = " . $sum ;
} else {
echo $message ;
}
echo '</td></tr>' ;
}
?>
</form>
</table>
</body>
</html>
|
注意:上述文件jsq.php需要上传至web服务器的根目录才能被正确解释执行。
效果如图所示:
希望本文所述对大家php程序设计有所帮助。