Math的一些常用的数学运算(包括取整、保留几位小数等)

来源:互联网 发布:淘宝女装店铺介绍大全 编辑:程序博客网 时间:2024/04/28 07:17

1.求两个数中的最大值:Math.max()

public static int max(int a, int b) public static long max(long a, long b)public static float max(float a, float b) public static double max(double a, double b) 
2.求两个数中的最小值:Math.min()

public static int min(int a, int b) public static long min(long a, long b)public static float min(float a, float b) public static double min(double a, double b) 
3.计算一个数的绝对值:Math.abs()

public static int abs(int a) public static long abs(long a)public static float abs(float a) public static double abs(double a) 
4.求a的b次方:Math.pow()

public static double pow(double a, double b) 

注意,返回类型是double

与之容易混淆的是a<<b,表示的是a*(2的b次方)。

5.四舍五入取整:Math.round()

public static int round(float a) public static long round(double a)
注意,float型取整后是int型,而double取整后是long型

6.保留n位小数:自己封装方法,策略是先乘以10的n次方,取整后转化为浮点数,再除以10的n次方

public double SplitAndRound(double a, int n) {a = a * Math.pow(10, n);return (Math.round(a)) / (Math.pow(10, n));}
上面这个自己封装的方法就可以把一个double型小数四舍五入保留n位小数。


0 0
原创粉丝点击