java 如何计算
基本数学运算
Java支持标准的数学运算符,包括加法(+)、减法(-)、乘法(*)、除法(/)和取模(%)。
int a = 10;
int b = 3;
int sum = a + b; // 13
int difference = a - b; // 7
int product = a * b; // 30
int quotient = a / b; // 3 (整数除法)
int remainder = a % b; // 1
浮点数运算
使用double或float类型进行浮点数计算时需注意精度问题。
double x = 10.0;
double y = 3.0;
double result = x / y; // 3.3333333333333335
使用 Math 类
Java的Math类提供常用数学函数,如幂、平方根、三角函数等。
double power = Math.pow(2, 3); // 8.0
double sqrt = Math.sqrt(16); // 4.0
double sinValue = Math.sin(Math.PI / 2); // 1.0
大数计算
处理大整数或高精度浮点数时,可使用BigInteger和BigDecimal类。
BigInteger bigInt = new BigInteger("12345678901234567890");
BigInteger sum = bigInt.add(new BigInteger("1")); // 12345678901234567891
BigDecimal decimal = new BigDecimal("0.1");
BigDecimal total = decimal.add(new BigDecimal("0.2")); // 0.3
位运算
Java支持位运算,如与(&)、或(|)、异或(^)、左移(<<)和右移(>>)。
int num1 = 5; // 0101
int num2 = 3; // 0011
int andResult = num1 & num2; // 0001 (1)
int orResult = num1 | num2; // 0111 (7)
表达式求值
Java遵循运算符优先级规则,可通过括号明确运算顺序。

int result = 2 + 3 * 4; // 14 (乘法优先)
int groupedResult = (2 + 3) * 4; // 20






