面向对象-------Math类(十七)

 A:Math类概述
    * 类包含用于执行基本数学运算的方法
B:Math类特点
    * 由于Math类在java.lang包下,所以不需要导包。
    * 因为它的成员全部是静态的,所以私有了构造方法
C:获取随机数的方法
    * public static double random():返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。
D:我要获取一个1-100之间的随机数
    * int number = (int)(Math.random()*100)+1;

class Demo2_Math {
	public static void main(String[] args) {
		//double d = Math.random();
		//System.out.println(d);
		
		//Math.random()会生成大于等于0.0并且小于1.0的伪随机数
		for (int i = 0;i < 10 ;i++ ) {
			System.out.println(Math.random());
		}

		//生成1-100的随机数
		//Math.random()0.0000000 - 0.999999999
		//Math.random() * 100 ====> 0.00000 - 99.999999999
		//(int)(Math.random() * 100) ====> 0 - 99
		//(int)(Math.random() * 100) + 1

		for (int i = 0;i < 10 ;i++ ) {
			System.out.println((int)(Math.random() * 100) + 1);
		}
	}
}

import java.util.Scanner;
class Test1_GuessNum {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);		//创建键盘录入对象
		System.out.println("请输入一个整数,范围在1-100之间");
		int guessNum = (int)(Math.random() * 100) + 1;	//心里想的随机数
		while (true) {			//因为需要猜很多次,所以用无限循环
			int result = sc.nextInt();	//大家猜的数
                    /*
                    如果你们猜的数大于了我心里想的数.提示大了;
                    如果你们猜的数小于了我心里想的数,提示小了;
                    否则,中了.
                      */
			if (result > guessNum) {					
		         System.out.println("大了");					
			} else if (result < guessNum) {					
				System.out.println("小了");				
			} else {							
				System.out.println("中了");				
				break;
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/mqingo/article/details/82110352