使用接口编写对任意两个数进行四则运算的程序
时间: 2024-05-29 12:09:56 浏览: 29
public interface ArithmeticOperation {
double add(double num1, double num2);
double subtract(double num1, double num2);
double multiply(double num1, double num2);
double divide(double num1, double num2);
}
public class Calculator implements ArithmeticOperation {
public double add(double num1, double num2) {
return num1 + num2;
}
public double subtract(double num1, double num2) {
return num1 - num2;
}
public double multiply(double num1, double num2) {
return num1 * num2;
}
public double divide(double num1, double num2) {
if (num2 == 0) {
throw new IllegalArgumentException("Cannot divide by zero");
}
return num1 / num2;
}
}
public class Main {
public static void main(String[] args) {
ArithmeticOperation calculator = new Calculator();
double num1 = 10.0;
double num2 = 5.0;
System.out.println(num1 + " + " + num2 + " = " + calculator.add(num1, num2));
System.out.println(num1 + " - " + num2 + " = " + calculator.subtract(num1, num2));
System.out.println(num1 + " * " + num2 + " = " + calculator.multiply(num1, num2));
System.out.println(num1 + " / " + num2 + " = " + calculator.divide(num1, num2));
}
}
阅读全文