Math类:
(1)针对数学运算进行操作的类
(2)常见方法
A:public static int abs(int a):绝对值
B:public static double ceil(double a):向上取整
C:public static double floor(double a):向下取整
D:public static int max(int a,int b):最大值 min最小值
E:public static double pow(double a,double b):a的b次幂
F:public static double random():随机数 [0.0,1.0)
G:public static int round(float a) 四舍五入(也有参数为double的)
H:public static double sqrt(double a):正平方根
(3)案例:
A:猜数字小游戏
B:获取任意范围的随机数
package cn.itcast_02;
import java.util.Scanner;
/*
* 需求:请设计一个方法,可以实现获取任意范围内的随机数。
*
* 分析:
* A:键盘录入两个数据。
* int strat;
* int end;
* B:想办法获取在start到end之间的随机数
* 我写一个功能实现这个效果,得到一个随机数。(int)
* C:输出这个随机数
*/
public class MathDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入开始数:");
int start = sc.nextInt();
System.out.println("请输入结束数:");
int end = sc.nextInt();
for (int x = 0; x < 100; x++) {
// 调用功能
int num = getRandom(start, end);
// 输出结果
System.out.println(num);
}
}
/*
* 写一个功能 两个明确: 返回值类型:int 参数列表:int start,int end
*/
public static int getRandom(int start, int end) {
int number = (int) (Math.random() * (end - start + 1)) + start;
return number;
}
}