java中如何计算
基本算术运算
Java支持基本的算术运算,包括加法、减法、乘法、除法和取模。
int a = 10;
int b = 3;
int sum = a + b; // 加法
int difference = a - b; // 减法
int product = a * b; // 乘法
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.333...
数学函数
Java的Math类提供了丰富的数学函数,如平方根、幂、三角函数等。

double sqrt = Math.sqrt(16); // 平方根,结果为4.0
double power = Math.pow(2, 3); // 幂运算,结果为8.0
double sin = Math.sin(Math.PI / 2); // 正弦函数,结果为1.0
位运算
Java支持位运算,包括与、或、异或、左移和右移。
int num1 = 5; // 二进制 0101
int num2 = 3; // 二进制 0011
int and = num1 & num2; // 与运算,结果为1 (0001)
int or = num1 | num2; // 或运算,结果为7 (0111)
int xor = num1 ^ num2; // 异或运算,结果为6 (0110)
int leftShift = num1 << 1; // 左移,结果为10 (1010)
int rightShift = num1 >> 1; // 右移,结果为2 (0010)
大数运算
对于超大整数或高精度计算,使用BigInteger和BigDecimal类。

import java.math.BigInteger;
import java.math.BigDecimal;
BigInteger bigInt1 = new BigInteger("12345678901234567890");
BigInteger bigInt2 = new BigInteger("98765432109876543210");
BigInteger sum = bigInt1.add(bigInt2); // 加法
BigDecimal decimal1 = new BigDecimal("123.456");
BigDecimal decimal2 = new BigDecimal("789.012");
BigDecimal product = decimal1.multiply(decimal2); // 乘法
随机数生成
使用Math.random()或Random类生成随机数。
double random = Math.random(); // 生成0.0到1.0之间的随机数
import java.util.Random;
Random rand = new Random();
int randomInt = rand.nextInt(100); // 生成0到99之间的随机整数
时间计算
使用System.currentTimeMillis()或Instant类计算时间差。
long startTime = System.currentTimeMillis();
// 执行某些操作
long endTime = System.currentTimeMillis();
long duration = endTime - startTime; // 计算耗时(毫秒)






