如何获取一个随机数:10-99
题目描述:
如何获取一个随机数:10-99,考察了强制类型转换。
解题思路:
random生成的是double型 [0.0,1.0)
公式:[a,b]:(int)(Math.random() * (b - a + 1) + a)
记住这个公式就没有问题
强制类型转换:自动类型提升运算的逆运算。
1.需要使用强转符:()
2.注意点:强制类型转换,可能导致精度损失。
代码举例如下:
//day02 --> VariableTest3
double d1 = 12.3;
//int i1 = d1;编译不通过
int i1 = (int)d1;//截断操作,取整数部分,不是四舍五入(此处精度损失)
System.out.println(i1);
long l1 = 123;
short s2 = (short)l1;//此处没有精度损失
System.out.println(i1);
int i2 = 128;
byte b = (byte)i2;
System.out.println(b);//此处输出为-128,也算是精度损失
Java代码:
public class Random {
public static void main(String[] args) {
int value = (int)(Math.random() * 90 + 10);
//[0.0,1.0) --> [0.0,90.0) --> [10.0,100.0) --> [10,99]
System.out.println(value);
//random生成的是double型[0.0,1.0)
//公式:[a,b]:(int)(math.random() * (b - a + 1) + a)
}
}