日期:2014-05-20 浏览次数:20686 次
package com.csdn;
import java.util.Random;
public class Float {
Random r1 = new Random();
Random r2 = new Random();
public float generateFloat()
{
float f1 = r1.nextFloat();
int i = r2.nextInt(3);
float f2 = f1 + i;
if(f2 >= 1.22 && f2 <= 2.56)
return f2;
else
return generateFloat();
}
public static void main(String[] args) {
Float f = new Float();
long t1 = System.currentTimeMillis();
System.out.println(f.generateFloat());
long t2 = System.currentTimeMillis();
System.out.println("It takes " + (t2 - t1) + " ms");
}
}
public class Float {
public static float generateFloat1()
{
Random random = new Random();
float add=(float) (random.nextFloat()*1.34);//1.22-2.56之间的增量。增量的随机数范围在0~1.34之间
float randomFloat=(float) (add+1.22);//增量加上1.22以后整个区间的范围在1.22~2.56之间。
return randomFloat;
}
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
System.out.println(generateFloat1());
long t2 = System.currentTimeMillis();
System.out.println("It takes " + (t2 - t1) + " ms");
}
}
package j2se_519;
import java.math.BigDecimal;
/**
* 求1.22~2.56之间的随机小数(精确到小数点后2位)
*
* @author 王二麻子
*/
public class RandomDemo1 {
public static void main(String[] args) {
double d = 1.22 + Math.random() * (2.56 - 1.22);