Math类和Random类的学习

一、Math类

Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。  
常用的方法:
public static int abs(int a):绝对值
public static double ceil(double a):向上取整
public static double floor(double a):向下取整
public static int max(int a,int b):求最大值
public static int min(int a,int b):求最小值
public static double pow(double a,double b):a的b次幂
public static double random()返回带正号的 double 值,该值大于等于 0.0 且小于 1.0
public static int round(float a):四射五入
public static double sqrt(double a):一个数的正平方根
JDK5的特性:静态导入(导入方法的级别), 这个一般不怎么常用,举个例子 :
import static java.lang.System.out;//导入java.lang包下的System类的静态方法out;
public class HelloWorld{
        public static void main(String[] args){
                out.print("Hello World!");//这里不用再写成System.out.println("Hello World!")了
                                          //因为已经导入了这个静态方法out.
        }
}

import xxxx 和 import static xxxx的区别是前者一般导入的是类文件如import java.util.Scanner;后者一般是导入静态的方法,import static java.lang.System.out;

说回Math类,我们通过一个例子学习一下它的方法:

public class MathDemo {
		
	public static void main(String[] args) {
		
		//public static int abs(int a):绝对值
		System.out.println(Math.abs(-10));
		System.out.println(Math.abs(10));
		
		//public static double ceil(double a):向上取整
		System.out.println(Math.ceil(12.34));
		
		//public static double floor(double a):向下取整
		System.out.println(Math.floor(12.34));
		
		//public static int max(int a,int b):求最大值
		System.out.println(Math.max(10, 20));
		
		//方法中嵌套方法
		//方法递归(方法本身调用方法的这种现象)
		//这里是方法嵌套
		System.out.println(Math.max(Math.max(10, 20), 20));
		
		//public static double pow(double a,double b):a的b次幂
		System.out.println(Math.pow(2.0, 3.0));
		
		//public static double random()返回带正号的 double 值,该值大于等于 0.0 且小于 1.0
		System.out.println(Math.random());
		
		//public static int round(float a):四射五入
		System.out.println(Math.round(12.56));
		
		//public static double sqrt(double a):一个数的正平方根
		System.out.println(Math.sqrt(4));	
	}	
}	

这里有个面试题:

有两个变量,让他们的值进行互换 我们可能会想到中间变量的方法来进行互换,但考官想问的是你能否知道位^的特点:一个数据被另一个数据位^两次,其值是它本身,(但在实际开发中还是采取中间变量的方式进行互换)
int a = 10 ;
int b = 20 ;

所以这里通过位运算来解决:

                a = a ^ b ; 
b = a ^ b ;    // b = (a^b)^b;
a = a ^ b ;    // a = (a ^b)^(a^b^b);


二、Random类

Random:是一个可以获取随机数的类

构造方法:
        public Random():无参构造方法
        public Random(long seed) :指定long类型的数据进行构造随机数类对象 
常用方法:
        public int nextInt():获取随机数,它的范围是在int类型范围之内

        public int nextInt(int n):获取随机数,它的范围是在[0,n)之间

public class RandomDemo {
	
	public static void main(String[] args) {
		
		//创建Random类对象
		Random r = new Random() ;
		
		for(int x = 0 ; x < 10 ; x ++) {
			int n = r.nextInt(5) ;
			System.out.println(n);
		}
	}
}
这个程序的作用是打印10次int类型的[0,5)的随机值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值