编写程序,实现加减乘除、平方和开方计算。(Java语言)
时间: 2024-09-12 16:09:06 浏览: 35
在Java中,我们可以创建一个名为`Calculator`的类,然后通过继承和重写抽象方法来实现加减乘除、平方和开方的功能。这里是一个简单的例子:
```java
import java.lang.Math;
abstract class BasicMathOperation {
abstract double performOperation(double a, double b);
}
class Calculator extends BasicMathOperation {
@Override
public double add(double a, double b) {
return a + b;
}
@Override
public double subtract(double a, double b) {
return a - b;
}
@Override
public double multiply(double a, double b) {
return a * b;
}
@Override
public double divide(double a, double b) {
if (b != 0) {
return a / b;
} else {
throw new IllegalArgumentException("Division by zero is not allowed.");
}
}
// 平方函数
public double square(double num) {
return Math.pow(num, 2);
}
// 开方函数
public double squareRoot(double num) {
if (num >= 0) {
return Math.sqrt(num);
} else {
throw new IllegalArgumentException("Cannot calculate square root of a negative number.");
}
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println("Addition: " + calculator.add(5, 3));
System.out.println("Subtraction: " + calculator.subtract(10, 4));
System.out.println("Multiplication: " + calculator.multiply(6, 2));
System.out.println("Division: " + calculator.divide(15, 5));
System.out.println("Square: " + calculator.square(4));
System.out.println("Square Root: " + calculator.squareRoot(9));
}
}
```
在这个程序中,`Calculator`类实现了`BasicMathOperation`接口,并提供了各种数学操作的具体实现。在`main`方法中,我们创建了一个`Calculator`实例并进行了计算。
阅读全文