AP计算机A自学笔记:Math类

Math类提供了运算符如绝对值,平方,开方,三角函数,对数等,还包括π和e等常数

实例程序:

package standardClasses;

import static java.lang.Math.*;
/*
the statuc import construct allows you to use the static method
of a class without the class name refix
 */

public class TheMathClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(abs(-5));	//return the absolute value
		//equavelent to:
		System.out.println(Math.abs(-5));
		
		
		System.out.println(abs(-4.5));
		System.out.println(pow(5, 10));	//return base(first) ^ exp(second), base >= 0 exp is an integer
		System.out.println(sqrt(25));	//return the square root
		System.out.println(random());	//return a random number between 0 and 1
		System.out.println(PI);	//comstant π
		System.out.println(E);	//constant e
		
	}

}

Math类所有的函数和常数都是静态方法,因此不存在Math对象

静态引入可以在不加类名前缀使用一个类里面的静态方法。如在Math类使用静态引入import static java.lang.Math.*; 允许直接写函数名,而非Math.函数

随机数

Math.random();

该函数可以生成0。0至1。0的随机数,包括0.0,但不包括1.0.
可以移动或者扩大该范围,如:


		//test random number
		System.out.println(6 * Math.random());	//0.0 <= x < 6.0
		System.out.println(Math.random() + 2);	//2.0 <= x < 3.0
		System.out.println(2 * Math.random() + 5);	//5.0 <= x < 7.0
		//general form
		int highValue = 8;
		int lowValue = 5;
		double x = (highValue - lowValue) * Math.random() + lowValue;	//lowValue <= x < highValue

随机整数
把随机数结果强转为int可以得到任意随机整数

其中Math.random()所乘的数叫做scaling factor

//test random integer
		System.out.println((int)(Math.random() * 100));		//integer from 0 to 99
		int a = (int)Math.random() * 100; 	//error: always zero, because casting is prior to multiply
		//general approach
		int k = 20;		//k is called scaling factor
		System.out.println((int)(Math.random() * k));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值