Java-使用Math,实现lg、平方、开方、round、floor、ceil

x33g5p2x  于2022-05-23 转载在 Java  
字(2.0k)|赞(0)|评价(0)|浏览(412)

一、lg

使用方法:Math.log10()

  1. public class MathMethod {
  2. public static void main(String[] args) {
  3. int a=100;
  4. double b=100;
  5. float c=100;
  6. System.out.println("lg的实现:"+Math.log10(a));
  7. System.out.println("lg的实现:"+Math.log10(b));
  8. System.out.println("lg的实现:"+Math.log10(c));
  9. }
  10. }
  11. //输出:
  12. //lg的实现:2.0
  13. //lg的实现:2.0
  14. //lg的实现:2.0

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

二、平方

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

  1. public class MathMethod {
  2. public static void main(String[] args) {
  3. int a=100;
  4. System.out.println("100的平方:"+Math.pow(a,2));
  5. }
  6. }
  7. //输出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类型

  1. public class MathMethod {
  2. public static void main(String[] args) {
  3. int a=100;
  4. System.out.println("100的开方(sqrt):"+Math.sqrt(a));
  5. System.out.println("100的开方(pow):"+Math.pow(a, 0.5));
  6. }
  7. }
  8. //输出
  9. //100的开方(sqrt):10.0
  10. //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。

  1. int java.lang.Math.round(float a) //float的入参返回int型
  2. 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)

  1. public class MathMethod {
  2. public static void main(String[] args) {
  3. int a=98;
  4. double b=-98.1;
  5. float c=98.8f;
  6. System.out.println("floor(98):"+Math.floor(a));
  7. System.out.println("floor(-98.1):"+Math.floor(b));
  8. System.out.println("floor(98.8f):"+Math.floor(c));
  9. System.out.println("ceil(98):"+Math.ceil(a));
  10. System.out.println("ceil(-98.1):"+Math.ceil(b));
  11. System.out.println("ceil(98.8f):"+Math.ceil(c));
  12. }
  13. }
  14. //输出:
  15. //floor(98):98.0
  16. //floor(-98.1):-99.0
  17. //floor(98.8f):98.0
  18. //ceil(98):98.0
  19. //ceil(-98.1):-98.0
  20. //ceil(98.8f):99.0

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

相关文章

最新文章

更多