Math类

概述:java.lang.Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。类似这样的工具 类,其所有方法均为静态方法,并且不会创建对象,调用简单。 

基本运算的方法:

  • public static double abs(double a) :返回 double 值的绝对值。 
  • public static double ceil(double a) :返回大于等于参数的小的整数。

  • public static double floor(double a) :返回小于等于参数大的整数。

  • public static long round(double a) :返回接近参数的 long。(相当于四舍五入方法)  
/**
* public static double abs(double a) :返回 double 值的绝对值。
* public static double ceil(double a) :返回大于等于参数的小的整数。
* public static double floor(double a) :返回小于等于参数大的整数。
* public static long round(double a) :返回接近参数的 long。(相当于四舍五入方法)
*/
public class MathTest01 {
public static void main(String[] args) {
//public static double abs(double a) :返回 double 值的绝对值。
double b1 = Math.abs(5.5);//5.5
double b2 = Math.abs(-5.5);//5.5
System.out.println(b1+" "+b2);

//public static double ceil(double a) :返回大于等于参数的小的整数。
double c1 = Math.ceil(5.1);//6.0
double c2 = Math.ceil(5.9);//6.0
double c3 = Math.ceil(-5.1);//-5.0
System.out.println(c1+" "+c2+" "+c3);

//public static double floor(double a) :返回小于等于参数大的整数。
double f1 = Math.floor(5.1);//5.0
double f2 = Math.floor(5.9);//5.0
double f3 = Math.floor(-5.1);//-6.0
System.out.println(f1+" "+f2+" "+f3);

//public static long round(double a) :返回接近参数的 long。(相当于四舍五入方法)
long r1 = Math.round(5.1);//5
long r2 = Math.round(5.9);//6
long r3 = Math.round(-5.1);//-5
System.out.println(r1+" "+r2+" "+r3);
}
}
  • 计算在 -10.8 到 5.9 之间,绝对值大于 6 或者小于 2.1 的整数有多少个? 
/**
* 计算在 -10.8 到 5.9 之间,绝对值大于 6 或者小于 2.1 的整数有多少个?
*/
public class MathTest02 {
public static void main(String[] args) {
//定义最大值
double max = 5.9;
//定义最小值
double min = -10.8;
int count = 0;
//在范围内循环
for (double i = Math.ceil(min); i <max ; i++) {
if(Math.abs(i)>6||Math.abs(i)<2.1){
count++;
}
}
System.out.println(count);
}
}

 

    

原文地址:https://www.cnblogs.com/lifengSkt/p/13260846.html