java第二讲
1.java.alng.Math类,通过类名.方法名的方式进行调用。
如 Math.sqrt(900.0); //double
JDK5.0开始,支持一种称为“静态导入”的方法:
import static java.lang.Math.*; //static *
sqrt(900);
2.Math.random()生成随机数
(int)(Math.random()*6); //[0,6)
(int)(Math.random()*6+1); //[0,6]
(int)(5+Math.random()*6+1); //[5,11]
3.Random.nextInt()生成随机数
Random r = new Random();
Random ran = new Random(System.currentTimeMillis());//以当前时间作为种子
//r.nextDouble
n = r.nextInt(10); //[0,10)
n = r.nextInt(11); //[0,10]
n = r.nextInt(10)+5; //[5,15)
min=10, max=120 [10,120]
n = r.nextInt(max-min+1)+min;
4.BigInteger类
//
Scanner in = new Scanner(System.in);
BigInteger big = in.nextBigInteger();
BigInteger big = new BigInteger("123356789900");
BigInteger big = new BigInteger(str);
int k=5678;
BigInteger big = BigInteger.valueOf(k);
String str = "1011100111";
int radix = 2; // radix代表二进制,为下一行代码中的参数radix赋值
BigInteger interNum1 = new BigInteger(str,radix); //743
// 1)加减乘除
a.add(b) a.subtract(b) a.multiply(b) a.divide(b)
// 2)String类型和BigInteger类型的转变
String str1="11223344556677889900";
BigInteger big=new BigInteger(str1);
String str2=String.valueOf(big);
// 3)BigInteger类型取随机数
public BigInteger nextRandom(BigInteger n){
Random r = new Random();
BigInteger big = new BigInteger(n.bitLength(),r);
//n=255 n.bitLength()=8 11111111
//n=256 n.bitlength()=9 (至少9位)
// =0:表示等于n,<0:表示小于n,>0表示大于n
while(big.compareTo(n)>=0){
big = new BigInteger(n.bitLength(),r);
}
return big;
}
BigInteger big = new BigInteger(64,new Random()); //[0-2的64次方]
5.BigDecimal类
Scanner in = new Scanner(System.in);
BigDecimal min,max;
min=in.nextBigDecimal();
max=in.nextBigDecimal();
float mmin,mmax;
mmin=min.floatValue();
mmax=max.floatValue();
BigDecimal big = new BigDecimal(Math.random()*(mmax-mmin)+mmin); //(mmax-mmin)
System.out.println(big.setScale(2, BigDecimal.ROUND_DOWN)); //保留2位小数点,不进行四舍五入
System.out.println(bd.setScale(2, BigDecimal.ROUND_HALF_UP));//进行四舍五入
6.可变参数
public static double max(double...values)
{
double largest=Double.MIN_VALUE;
for (double v:values)
if(v>largest) largest=v;
return largest;
}
调用:max(1,23,34,55,33,22,11);
返回:55.0
7.浮点型运算误差。
借助 if(Math.abs(a-b)<1e-10)