PHP实现计算器小功能
本文实例为大家分享了PHP实现计算器小功能的具体代码,供大家参考,具体内容如下
<?php
if (isset($_POST['sub'])) {
$f = true;
$error = "有以上问题: <br>";
if ($_POST["num1"] == "") {
$f = false;
$error .= "第一个数不能为空.<br>";
} else {
if(!is_numeric($_POST[num1])) {
$f = false;
$error .= "第一个数字不是数字.<br>";
}
}
if ($_POST['num2'] == "") {
$f = false;
$error .= "第二个数字不能为空.<br>";
} else {
if (!is_numeric($_POST['num2'])) {
$f = false;
$error .= "第二个数字不是数字<br>";
}
}
if ($f) {
switch ($_POST['ysf']) {
case '+': $sum = $_POST['num1']+$_POST['num2'];
break;
case '-': $sum = $_POST['num1']-$_POST['num2'];
break;
case '*': $sum = $_POST['num1']*$_POST['num2'];
break;
case '/': $sum = $_POST['num1']/$_POST['num2'];
break;
case '%': $sum = $_POST['num1']%$_POST['num2'];
break;
}
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>简易计算器</title>
<style>
* {
margin: 0px;
padding: 0px;
}
#contains {
width: 400px;
margin: 50px auto;
}
h1 {
width: 400px;
text-align: center;
color: #0F0;
}
table {
margin-top: 20px;
width: 400px;
}
input {
background: yellow;
border-radius: 20px;
}
input:hover {
background: green;
}
select {
background: yellow;
border-radius: 20px;
}
td {
background: #3F0;
text-align: center;
height: 30px;
}
#sub {
border-radius: 25px;
width: 50px;
}
</style>
</head>
<body>
<div id="contains">
<h1>简易计算器</h1>
<form action="Calculator.php" method="post">
<table border="0">
<tr>
<td><input type="text" name="num1" value="<?php echo $_POST['num1'];?>" size="3"/></td>
<td>
<select name="ysf">
<option <?php if($_POST['ysf'] == "+") echo "selected";?> value="+">+</option>
<option <?php if($_POST['ysf'] == "-") echo "selected";?> value="-">-</option>
<option <?php if($_POST['ysf'] == "*") echo "selected";?> value="*">*</option>
<option <?php if($_POST['ysf'] == "/") echo "selected";?> value="/">/</option>
<option <?php if($_POST['ysf'] == "%") echo "selected";?> value="%">%</option>
</select>
</td>
<td><input type="text" name="num2" value="<?php echo $_POST['num2'];?>" size="3"/></td>
<td><input type="submit" id = 'sub' name="sub" value="计算"/></td>
</tr>
<tr>
<td colspan="4">
<?php
if ($f) {
echo "计算结果: <b>{$_POST['num1']}{$_POST['ysf']}{$_POST['num2']} = {$sum}</b>";
} else {
echo "<b>$error</b>";
}
?>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
以上是 PHP实现计算器小功能 的全部内容, 来源链接: utcz.com/p/224544.html