Java入门学习-使用Math,实现lg、平方、开方、round、floor、ceil的算法。

xiaoxiao2021-02-27  496

一、lg

使用方法:Math.log10()

public class MathMethod { public static void main(String[] args) { int a=100; double b=100; float c=100; System.out.println("lg的实现:"+Math.log10(a)); System.out.println("lg的实现:"+Math.log10(b)); System.out.println("lg的实现:"+Math.log10(c)); } } //输出: //lg的实现:2.0 //lg的实现:2.0 //lg的实现:2.0

然后Math.log10()返回的是double型的,所以当它赋值给int时,会报错。 还有两种log方法: Math.log():求以2为底的对数 Math.log1p():求Ln(X+ 1)

二、平方

使用方法:Math.pow(x,y):求x的y次方 同样也是返回double类型

public class MathMethod { public static void main(String[] args) { int a=100; System.out.println("100的平方:"+Math.pow(a,2)); } } //输出100的平方:10000.0

三、开方

使用方法: 1、Math.sqrt(a):求a的开平方 2、Math.pow(a,1.0/b):求a的开b次方。 假设是开3次方,这里需要注意的是1.0/3.0,不能写1/3哦。因为前者返回的是double类型,保留了小数,后者是int型,会自动取整(向下取0了)。 同样也是返回double类型

public class MathMethod { public static void main(String[] args) { int a=100; System.out.println("100的开方(sqrt):"+Math.sqrt(a)); System.out.println("100的开方(pow):"+Math.pow(a, 0.5)); } } //输出 //100的开方(sqrt):10.0 //100的开方(pow):10.0

四、round

四舍五入:算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整(小数位<5就不加了),所以: Math.round(98.5)的结果为99, Math.round(-98.5)的结果为-98, Math.round(-98.6)的结果为-99。

int java.lang.Math.round(float a) //float的入参返回int型 long java.lang.Math.round(double a) //double的入参返回long型

五、floor和ceil

我是这么记忆的:floor是地板的意思,就是向下取整;ceil是天花板,就是向上取整。 double java.lang.Math.floor(double a) double java.lang.Math.ceil(double a)

public class MathMethod { public static void main(String[] args) { int a=98; double b=-98.1; float c=98.8f; System.out.println("floor(98):"+Math.floor(a)); System.out.println("floor(-98.1):"+Math.floor(b)); System.out.println("floor(98.8f):"+Math.floor(c)); System.out.println("ceil(98):"+Math.ceil(a)); System.out.println("ceil(-98.1):"+Math.ceil(b)); System.out.println("ceil(98.8f):"+Math.ceil(c)); } } //输出: //floor(98):98.0 //floor(-98.1):-99.0 //floor(98.8f):98.0 //ceil(98):98.0 //ceil(-98.1):-98.0 //ceil(98.8f):99.0

需要注意的是:负数调用Math的各方法 round(-98.5):-98 round(-98.6):-99。 floor(-98.1):-99.0 ceil(-98.1):-98.0

转载请注明原文地址: https://www.6miu.com/read-2127.html

最新回复(0)