今天遇到一个问题:如何随机生成50-100之间的保留两位小数的数字。
所以打算总结一下
一、定义
函数 | 含义 | 形式 |
Math.ceil() | 向上取整数,即返回大于等于(>=)给定参数的最小整数,返回类型为double | public static double ceil(double a) |
Math.floor() | 向下取整,即返回小于等于(<=)给定参数的最大整数,返回类型为double | |
Math.rint() | 返回与参数最接近的整数,如果两边一样接近,那么选取偶数。返回类型为double | public static double rint(double a) |
Math.round() | 表示四舍五入,返回的类型为double | public static double round(double a)
|
二、实例
1、Math.ceil()函数
double testdate=3.14;
System.out.println("Math.ceil("+testdate+")所对应的值为"+ Math.ceil(testdate));
testdate=-3.14;
System.out.println("Math.ceil("+testdate+")所对应的值为"+ Math.ceil(testdate));
结果:
Math.ceil(3.14)所对应的值为4.0
Math.ceil(-3.14)所对应的值为-3.0
2、Math.floor()函数
double testdate=3.14;
System.out.println("Math.ceil("+testdate+")所对应的值为"+ Math.floor(testdate));
testdate=-3.14;
System.out.println("Math.ceil("+testdate+")所对应的值为"+ Math.floor(testdate));
结果:
Math.floor(3.14)所对应的值为3.0
Math.floor(-3.14)所对应的值为-4.0
3、Math.rint()
double testdate=3.14;
System.out.println("Math.rint("+testdate+")所对应的值为"+ Math.rint(testdate));
testdate=-3.14;
System.out.println("Math.rint("+testdate+")所对应的值为"+ Math.rint(testdate));
testdate=3.5;
System.out.println("Math.rint("+testdate+")所对应的值为"+ Math.rint(testdate));
testdate=4.5;
System.out.println("Math.rint("+testdate+")所对应的值为"+ Math.rint(testdate));
结果:
Math.rint(3.14)所对应的值为3.0
Math.rint(-3.14)所对应的值为-3.0
Math.rint(3.5)所对应的值为4.0
Math.rint(4.5)所对应的值为4.0
4、Math.round()
double testdate=3.14;
System.out.println("Math.round("+testdate+")所对应的值为"+ Math.round(testdate));
testdate=-3.14;
System.out.println("Math.round("+testdate+")所对应的值为"+ Math.round(testdate));
testdate=3.5;
System.out.println("Math.round("+testdate+")所对应的值为"+ Math.round(testdate));
testdate=4.5;
System.out.println("Math.round("+testdate+")所对应的值为"+ Math.round(testdate));
结果:
Math.round(3.14)所对应的值为3
Math.round(-3.14)所对应的值为-3
Math.round(3.5)所对应的值为4
Math.round(4.5)所对应的值为5
总结: ceil为天花板,所以向上取整。
floor为地板,所以向下取整
rint为关系进,相同情况下取偶数
round为圆滑一些,四舍五入看情况
三、综合应用
问题一:随机生成(a,b)之间的保留两位小数的双精度类型的数据.例如3.14
实现代码:
public class Main {
public str random()
{
String read=null;
Double StartData=0.0,EndData=0.0;
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入开始区间");
try {
read=bufferedReader.readLine();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
StartData= Double.parseDouble(read);
System.out.println("请输入结束区间");
try {
read=bufferedReader.readLine();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
//结束区间
EndData=Double.parseDouble(read);
System.out.println("区间为["+StartData+","+EndData+"]");
int current=2;
//保留的位数
double c=Math.floor((Math.random()*(EndData-StartData)+StartData)*Math.pow(10, 2))/Math.pow(10, 2);
DecimalFormat df = new DecimalFormat( "0.00" );
String str=df.format( c );
return str;
}
public static void main(String args[])
{ Main aMain=new Main();
System.out.println("结果为"+aMain.random());
}
}