zoukankan      html  css  js  c++  java
  • 常用Java API:Math类

    求最值

    最小值

    Math.min(int a, int b)
    Math.min(float a, float b)
    Math.min(double a, doubleb)
    Math.min(long a, long b)

    最大值

    Math.max(int a, int b)
    Math.max(float a, float b)
    Math.max(double a, doubleb)
    Math.max(long a, long b)

    Math.min() 和 Math.max() 方法分别返回一个最小值和一个最大值。
    实例:

    public class Main{
    	public static void main(String[] args){
    		int a = 10;
    		int b = 20;
    		System.out.println(Math.min(a, b));
    		System.out.println(Math.max(a, b));
    	}
    }
    

    求平方根

    Math.sqrt(double a)
    返回正确舍入的 double 值的正平方根。


    求绝对值

    Math.abs(double a)
    Math.abs(int a)
    Math.abs(flota)
    Math.abs(long)
    返回一个类型和参数类型一致的绝对值

    public class Main{
    	public static void main(String[] args){
    		int a = -10;
    		System.out.println(Math.abs(a));
    	}
    }
    

    求幂(a^b)

    Math.pow(double a, double b)
    注意无论是传入int还是long都会返回一个double类型的数。

    实例:
    img
    所以要求int类型的幂时,要对结果进行类型转换。

    取整

    1. Math.ceil(double x)
      向上取整,返回大于该值的最近 double 值

      System.out.println(Math.ceil(1.4)); // 2.0
      System.out.println(Math.ceil(-1.6)); // -1.0
      
    2. Math.floor(double x)
      向下取整,返回小于该值的最近 double 值

      System.out.println(Math.floor(1.6)); // 1.0
      System.out.println(Math.floor(-1.6)); // -2.0
      
    3. Math.round(double x);
      四舍五入取整

      System.out.println(Math.round(1.1)); // 1
      System.out.println(Math.round(1.6)); // 2
      System.out.println(Math.round(-1.1)); // -1
      System.out.println(Math.round(-1.6)); // -2
      

    得到一个随机数

    Math.random()
    生成一个[0,1)之间的double类型的伪随机数

    所以为了得到一个[1, b] 之间的整数可以这样做:

    int a = (int)(Math.random()*b + 1); // [1, b]
    

    如果要得到[a, b]的一个整数则是:

    int a = (int)(Math.random()*(b - a + 1) + a)  
    // + 1 是因为random()最大取不到1,所以上限取整后就会少1.   
    

    三角函数

    • Math.cos(double a) 余弦
    • Math.acos(double a) 反余弦
    • Math.sin(double a) 正弦值
    • Math.asin(double a) 反正弦值
    • Math.tan(double a) 正切值
    • Math.atan(double a) 反正切

    我们可以用acos()方法求π
    因为
    cos(π) = -1
    所以
    acos(-1) = π

  • 相关阅读:
    Java菜鸟之java基础语法,运算符(三)
    Lotus迁移到Exchange 2010 POC 之Domino Server的配置!
    hibernate:对于java.lang.NoSuchMethodError: antlr.collections.AST.getLine()I错误解决办法
    【targeting学习笔记】Display Advertising Targeting
    Domino 迁移到Exchange 之 Domino Admin 安装!
    sqlite3使用详解(Qt版本)
    .net反混淆脱壳工具de4dot的使用
    破解NET的四大神器(转)
    C#让应用程序只运行一个实例的几种方法
    Windows server 2008 R2实现多用户远程连接
  • 原文地址:https://www.cnblogs.com/wangzheming35/p/12304410.html
Copyright © 2011-2022 走看看