用php写一个计算器
时间: 2023-08-14 10:04:34 浏览: 96
php 计算器
好的,下面是一个简单的计算器 PHP 代码:
```php
<?php
if(isset($_POST['submit'])){
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$operator = $_POST['operator'];
$result = '';
switch($operator){
case 'add':
$result = $num1 + $num2;
break;
case 'sub':
$result = $num1 - $num2;
break;
case 'mul':
$result = $num1 * $num2;
break;
case 'div':
$result = $num1 / $num2;
break;
default:
$result = '';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Calculator</title>
</head>
<body>
<h1>PHP Calculator</h1>
<form method="post">
<label>Number 1:</label>
<input type="number" name="num1" required>
<br><br>
<label>Number 2:</label>
<input type="number" name="num2" required>
<br><br>
<label>Select Operator:</label>
<select name="operator">
<option value="add">Addition</option>
<option value="sub">Subtraction</option>
<option value="mul">Multiplication</option>
<option value="div">Division</option>
</select>
<br><br>
<input type="submit" name="submit" value="Calculate">
</form>
<?php if(isset($_POST['submit'])){ ?>
<h3>Result:</h3>
<p><?php echo $result; ?></p>
<?php } ?>
</body>
</html>
```
这个计算器可以通过选择不同的运算符来进行加减乘除运算。用户输入数字后,提交表单即可得到计算结果。
阅读全文