Math类—相关操作
-
abs—ceil—floor—round
package cn.xiaoge.day08.demo04; /* java.util.Math类是数学相关的工具类, 里面提供了大量的静态方法, 完成与数学运算相关的操作. public static double abs(double num): 获取绝对值. public static double ceil(double num): 向上取证. public static double floor(double nm): 向下取证. public static long round(double num): 四舍五入. Math.PI代表近似的圆周率常量(double). */ public class Demo03Math { public static void main(String[] args) { // 获取绝对值 System.out.println(Math.abs(3.14)); // 3.14 System.out.println(Math.abs(0)); // 0 System.out.println(Math.abs(-2.5)); // 2.5 System.out.println("======================"); // 向上取证 System.out.println(Math.ceil(19.3)); // 20.0 System.out.println(Math.ceil(19.8)); // 20.0 System.out.println(Math.ceil(19.0)); // 19.0 System.out.println("======================"); // 向下取证, 抹零 System.out.println(Math.floor(18.9)); // 18.0 System.out.println(Math.floor(18.0)); // 18.0 System.out.println(Math.floor(18.4)); // 18.0 System.out.println("======================"); // 四舍五入 System.out.println(Math.round(30.4)); // 30 System.out.println(Math.round(30.5)); // 31 } } // 运行结果 3.14 0 2.5 ====================== 20.0 20.0 19.0 ====================== 18.0 18.0 18.0 ====================== 30 31
-
练习题
package cn.xiaoge.day08.demo04; /* 题目: 计算-10.8到5.9之间, 绝对值大于6或者小于2.1的整数有多少个? 分析: 1. 既然已经确定了范围, for循环 2. 起点位置-10.8应该转换成为-10, 两种方法: 2.1 可以使用Math.ceil方法, 向上(向正方向)取整 2.2 强转成为int, 自动舍弃所有小数位 3. 每一个数字都是整数, 所以步进表达式应该是num++, 这样每次都是+1的. 4. 如何拿到绝对值: Math.abs方法 5. 一旦发现了一个数字, 需要让计数器++进行统计. 备注: 如果使用Math.ceil方法, -10.8可以变成-10.0. 注意double也是可以进行++的. */ public class Demo04MathPractise { public static void main(String[] args) { int count1 = 0; // 符合要求的数量 int count2 = 0; // 符合要求的数量 double min = -10.8; double max = 5.9; // 这样处理, 变量i就是期间之内所有的整数 for (int i = (int)min; i < max; i++) { if (Math.abs(i) > 6 || Math.abs(i) < 2.1) { System.out.print(i + " "); count1++; } } System.out.println(""); System.out.println("总共有: " + count1); System.out.println("========================="); // 这样处理, 变量i就是期间之内所有的整数 for (double i = Math.ceil(min); i < max; i++) { if (Math.abs(i) > 6 || Math.abs(i) < 2.1) { System.out.print(i + " "); count2++; } } System.out.println(""); System.out.println("总共有: " + count2); } } // 运行结果 -10 -9 -8 -7 -2 -1 0 1 2 总共有: 9 ========================= -10.0 -9.0 -8.0 -7.0 -2.0 -1.0 0.0 1.0 2.0 总共有: 9