php 完成简易计算器程序
时间: 2024-10-09 15:07:45 浏览: 61
在 PHP 中完成一个简单的计算器程序,可以使用基本的流程控制结构如条件语句(if-else)和循环来实现加、减、乘、除的功能。下面是一个基础示例:
```php
<?php
class Calculator {
public function add($num1, $num2) {
return $num1 + $num2;
}
public function subtract($num1, $num2) {
return $num1 - $num2;
}
public function multiply($num1, $num2) {
return $num1 * $num2;
}
public function divide($num1, $num2) {
// 需要检查除数是否为0,防止错误
if ($num2 != 0) {
return $num1 / $num2;
} else {
return "Error: Division by zero is not allowed.";
}
}
}
// 创建计算器实例
$calculator = new Calculator();
// 用户输入操作和数字
echo "Enter operation (+, -, *, /): ";
$operation = trim(fgets(STDIN));
echo "Enter first number: ";
$num1 = (float) fgets(STDIN);
echo "Enter second number: ";
$num2 = (float) fgets(STDIN);
// 根据用户输入执行相应的计算
switch ($operation) {
case '+':
echo "Result: " . $calculator->add($num1, $num2) . "\n";
break;
case '-':
echo "Result: " . $calculator->subtract($num1, $num2) . "\n";
break;
case '*':
echo "Result: " . $calculator->multiply($num1, $num2) . "\n";
break;
case '/':
echo $calculator->divide($num1, $num2);
break;
default:
echo "Invalid operation. Please use one of the following: +, -, *, /\n";
}
?>
阅读全文