用php语言写一个网页计算器
时间: 2024-10-19 07:07:14 浏览: 13
当然可以,下面是一个简单的PHP网页计算器的示例,它允许用户输入两个数字并执行基本的加减乘除运算:
```php
<!DOCTYPE html>
<html lang="zh">
<head>
<title>简单PHP计算器</title>
<style>
input[type=number] {
width: 50px;
}
</style>
</head>
<body>
<h1>简易PHP计算器</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="num1">Number 1:</label>
<input type="number" name="num1" id="num1"><br><br>
<label for="operator">Operator (+, -, *, /):</label>
<select name="operator" id="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select><br><br>
<label for="num2">Number 2:</label>
<input type="number" name="num2" id="num2"><br><br>
<input type="submit" name="calculate" value="Calculate">
</form>
<?php
if(isset($_POST['calculate'])) {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$operator = $_POST['operator'];
switch ($operator) {
case "+":
$result = $num1 + $num2;
break;
case "-":
$result = $num1 - $num2;
break;
case "*":
$result = $num1 * $num2;
break;
case "/":
// 需要考虑除数是否为零的情况
if($num2 != 0) {
$result = $num1 / $num2;
} else {
$result = "Error: Division by zero";
}
break;
default:
$result = "Invalid operator";
break;
}
echo "<p>Result: {$result}</p>";
}
?>
</body>
</html>
```
阅读全文