在 Java 中,进行四则运算(加法、减法、乘法、除法)有多种实现方式。以下是其中一些常见的方式,并附带详细的步骤流程、示例代码以及可能的第三方库依赖。
这是最常见的方法,使用 Java 中的基本运算符来执行四则运算。
步骤流程:
示例代码:
public class BasicArithmetic {
public static void main(String[] args) {
int a = 10;
int b = 5;
int additionResult = a + b;
int subtractionResult = a - b;
int multiplicationResult = a * b;
double divisionResult = (double) a / b; // Convert to double for accurate division
System.out.println("Addition: " + additionResult);
System.out.println("Subtraction: " + subtractionResult);
System.out.println("Multiplication: " + multiplicationResult);
System.out.println("Division: " + divisionResult);
}
}
Java 的 Math 类提供了一些静态方法来执行基本的数学运算。
步骤流程:
示例代码:
public class MathArithmetic {
public static void main(String[] args) {
int a = 10;
int b = 5;
int additionResult = Math.addExact(a, b);
int subtractionResult = Math.subtractExact(a, b);
int multiplicationResult = Math.multiplyExact(a, b);
double divisionResult = (double) a / b; // Convert to double for accurate division
System.out.println("Addition: " + additionResult);
System.out.println("Subtraction: " + subtractionResult);
System.out.println("Multiplication: " + multiplicationResult);
System.out.println("Division: " + divisionResult);
}
}
Apache Commons Math 是一个常用的数学库,提供了丰富的数学功能。
步骤流程:
示例代码:
import org.apache.commons.math3.util.ArithmeticUtils;
public class CommonsMathArithmetic {
public static void main(String[] args) {
int a = 10;
int b = 5;
int additionResult = ArithmeticUtils.addAndCheck(a, b);
int subtractionResult = ArithmeticUtils.subAndCheck(a, b);
int multiplicationResult = ArithmeticUtils.mulAndCheck(a, b);
double divisionResult = (double) a / b; // Convert to double for accurate division
System.out.println("Addition: " + additionResult);
System.out.println("Subtraction: " + subtractionResult);
System.out.println("Multiplication: " + multiplicationResult);
System.out.println("Division: " + divisionResult);
}
}
Gradle 依赖:
dependencies {
implementation group: 'org.apache.commons', name: 'commons-math3', version: '3.6.1'
}
Maven 依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
这些方法涵盖了 Java 中进行四则运算的不同方式,你可以根据自己的需求选择合适的方法来实现。