要点:
1.浮点型默认数据类型为double,若声明是浮点型,后面要加f或F。
2.float结果不精确。
测试程序:
/*
测试浮点型数据
*/
public class Primitive_type2 {
public static void main(String[] args){
float a = 15.7**f**; /*f一定要有
double b = 15.88;
float c = 15e-2f;
double d = 1101E-5;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
short x = 30000;
byte y = 100;
int popu = 2000000000;
float e = 0.1f;
double f = 1.0/10;
System.out.println(e);
System.out.println(f);
System.out.println(e==f); /*float结果不精确,值不相等
float k = 400003333f;
float k2 = k + 1;
if (k == k2){
System.out.println("k==k2!");
}else {
System.out.println("K!=K2!");
}
System.out.println("#######################################################");
BigDecimal bd = BigDecimal.valueOf(1.0);
bd = bd.subtract(BigDecimal.valueOf(0.1));
bd = bd.subtract(BigDecimal.valueOf(0.1));
bd = bd.subtract(BigDecimal.valueOf(0.1));
bd = bd.subtract(BigDecimal.valueOf(0.1));
bd = bd.subtract(BigDecimal.valueOf(0.1));
System.out.println(bd);
System.out.println(1.0-0.1-0.2-0.2);
BigDecimal bd2 = BigDecimal.valueOf(0.1);
BigDecimal bd3 = BigDecimal.valueOf(1/10.0);
System.out.println(bd2.equals(bd3)); /*结果为true!!
}
}
运行结果:
k竟然等于k2,可见float不要用于比较!不精确。