How to get a random number: 10-99
Topic description:
How to get a random number: 10-99, which examined the forced type conversion.
Problem-solving ideas:
Random generates a double type [0.0,1.0)
formula: [a,b]:(int)(Math.random() * (b-a + 1) + a)
Remember this formula, there is no problem
Coercive type conversion: the inverse operation of the automatic type promotion operation.
1. Need to use forced conversion: ()
2. Note: forced type conversion may lead to loss of precision.
The code example is as follows:
//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 code:
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)
}
}