• 常用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) = π

  • 相关阅读:
    在Asp.net 2.0使用页面无刷新
    Asp.net 2.0 中的TreeView的右键菜单(Context Menus on the TReeView IE Specific)
    利用XMLHTTP无刷新自动实时更新数据
    表单提交中Get和Post方式的区别
    一个好的学习asp.net 2.0的网站
    用WebService实现web页面的局部刷新
    GridView中的数据导出到Excel中
    Windows 桌面主题,桌面背景
    通过OleDB连接方式,访问Access,Excel数据库.
    转:VS.NET2005安装与设置指南
  • 原文地址:https://www.cnblogs.com/wangzheming35/p/12304410.html
Copyright © 2020-2023  润新知