首页 技术 正文
技术 2022年11月9日
0 收藏 456 点赞 4,743 浏览 1464 个字

求最值

最小值

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类型的数。

实例:

所以要求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) = π

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,077
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,552
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,400
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,813
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,895