编写后端php加减乘除以及求余的功能功能
时间: 2024-10-12 14:09:51 浏览: 26
在PHP中,你可以创建一个简单的函数来实现加减乘除以及取余的基本数学运算。这里是一个简单的例子:
```php
function perform_arithmetic_operations($num1, $num2, $operation) {
switch ($operation) {
case 'add':
return $num1 + $num2;
case 'subtract':
return $num1 - $num2;
case 'multiply':
return $num1 * $num2;
case 'divide':
if ($num2 != 0) {
return $num1 / $num2;
} else {
throw new Exception("Division by zero is not allowed.");
}
case 'modulus':
return $num1 % $num2;
default:
throw new Exception("Invalid operation. Please choose from: add, subtract, multiply, divide, modulus");
}
}
try {
$num1 = 10;
$num2 = 5;
echo "Addition: " . perform_arithmetic_operations($num1, $num2, 'add') . "\n";
echo "Subtraction: " . perform_arithmetic_operations($num1, $num2, 'subtract') . "\n";
echo "Multiplication: " . perform_arithmetic_operations($num1, $num2, 'multiply') . "\n";
echo "Division: " . perform_arithmetic_operations($num1, $num2, 'divide') . "\n";
echo "Modulus: " . perform_arithmetic_operations($num1, $num2, 'modulus') . "\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
```
这个函数接受两个数和一个字符串操作作为参数,根据操作字符串执行相应的数学运算。注意,除法(divide)特别处理了除以零的情况,而其他非法操作会被抛出异常。
阅读全文