java数学库

x33g5p2x  于2021-11-02 转载在 Java  
字(0.9k)|赞(0)|评价(0)|浏览(409)

一、最大值

查找x和 y 的最大值:Math.max(x,y)

  1. package test6;
  2. public class test1 {
  3. public static void main(String [] args)
  4. {
  5. System.out.println(Math.max(5, 10));
  6. }
  7. }

运行:

二、最小值

用于查找x 和y的最小值:Math.min(x,y)
举例:

  1. package test6;
  2. public class test2 {
  3. public static void main(String [] args)
  4. {
  5. System.out.println(Math.min(2,5));
  6. }
  7. }

运行:

三、开平方

返回x 的平方根:Math.sqrt(x)

举例如下:

  1. package test6;
  2. public class test3 {
  3. public static void main(String [] args)
  4. {
  5. System.out.println(Math.sqrt(9));
  6. }
  7. }

运行:

四、绝对值

回x的绝对(正)值:Math.abs(x)

比如求-5的绝对值:

  1. package test6;
  2. public class test4 {
  3. public static void main(String [] args)
  4. {
  5. System.out.println(Math.abs(-5));
  6. }
  7. }

运行:

五、随机数

Math.random() 返回 0.0(含)和 1.0(不含)之间的随机数:

  1. package test6;
  2. public class test5 {
  3. public static void main(String [] args)
  4. {
  5. System.out.println(Math.random());
  6. }
  7. }

运行:

为了更好地控制随机数,例如您只想要一个 0 到 100 之间的随机数,您可以使用以下公式:

  1. package test6;
  2. public class test6 {
  3. public static void main(String [] args)
  4. {
  5. int a = (int)(Math.random() * 101); // 0 到 100
  6. System.out.println(a);
  7. }
  8. }

运行:

这些是比较常见的数学库,一定要掌握。

相关文章

最新文章

更多