20-03-其他对象API(Math类)

来源:互联网 发布:淘宝自动打款时间 编辑:程序博客网 时间:2024/05/16 12:12
package cn.itcast.math.demo;public class MathDemo {public static void main(String[] args) {/* * 打开API中的java.lang包,找到Math类,发现Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。 *  * 该类中所有字段(自然对数底数E和圆周率PI)、方法均为静态的。 *  * Math:提供了操作数学运算的方法。 *  * 常用的方法(其余方法开发时候直接查找API即可): ceil(x):返回大于等于x的最小整数 floor(x):返回小于等于x的最大整数 * round(x):返回四舍五入的整数 pow(a,b):返回a的b次方 random():返回大于等于 0.0 且小于 1.0 * 的一个随机数。 */double d1 = Math.ceil(12.56);// 13.0double d2 = Math.floor(12.56);// 12.0double d3 = Math.round(12.56);// 13.0System.out.println(d1);System.out.println(d2);System.out.println(d3);double d = Math.pow(10, 2);System.out.println(d);// 100.0for (int i = 0; i < 9; i++) {double d4 = Math.random();System.out.println(d4);// 每次输出诸如0.02941423998320425之类的随机数,每次都不一样}// 需求,输出1到10的随机整数for (int i = 0; i < 10; i++) {double d5 = Math.ceil(Math.random() * 10);//【方法一】random取出的是0到1之间的随机小数,那么×10变成0到1之间的一个数,再用ceil取整,为了避免出现0.0的情况,这里用ceil而不是floorSystem.out.println(d5);double d6 = (int)(Math.random() * 10 + 1);//【方法二】System.out.println(d6);}}}

0 0