面试遇到的浮点数除0和余0、定义的选择题,小结一下
首先看代码
double a = 9.1;
double b = 0.0;
double e = 5.0;
double e2 = 5;
double e3 = 5.2;
//double v = a / e;
//double v1 = a / 5;
System.out.println(a / b); //-------------------结果 :Infinity
System.out.println("a/b == a/b " + (a / b == a / b));//a/b == a/b true
System.out.println("a%b " + a % b);//-------------------结果 :a%b NaN
System.out.println("a%b == a%b " + (a % b == a % b));//a%b == a%b false
System.out.println("a/e=" + a / e + " a%e:" + a % e);// a/e=1.8199999999999998 a%e:4.1
System.out.println("a/e2=" + a / e2 + " a%e:" + a % e2);// a/e=1.8199999999999998 a%e:4.1
System.out.println("a/e3=" + a / e3 + " a%e:" + a % e3);// a/e3=1.7499999999999998 a%e:3.8999999999999995
double d1 = 0.0 / 0.0;
double d11 = 0.0 / 0.0;
Double d22 = 0.0 / 0.0;
System.out.println("d1=" + d1 + " d1 == d1 "+ (d1 == d1));//d1=NaN d1 == d1 false
System.out.println(d1 == 1);
System.out.println(d1 == d11);//false
System.out.println(d22.equals(d1));//true
//float c = 2.0;//不合法 不能指为小数,指为小数必须加f 如float c2 = 2.0f;
float c2 = 2.0f;//合法
System.out.println();
float c = 2.3f;
float d = 0;
float d2 = 1;
float d3 = 1.0f;
float d4 = 1.5f;
System.out.println(c / d);//-------------------结果 :Infinity
System.out.println("c%d " + c % d);//-------------------结果 :c%d NaN
System.out.println("c/d2=" + c / d2 + " c%d2 " + c % d2);// c/d2=2.3 c%d2 0.29999995
System.out.println("c/d3=" + c / d3 + " c%d3 " + c % d3);// c/d2=2.3 c%d2 0.29999995
System.out.println("c/d4=" + c / d4 + " c%d4 " + c % d4);// c/d4=1.5333333 c%d4 0.79999995
结论:
- 浮点数除以0.0或0,得到Infinity或-Infinity,即正、负无穷。
- 浮点数模0结果为不是一个数,即NaN。
- Infinity == Infinity,而NaN != NaN。
- 定义float有小数必带f,double怎么都行。
正无穷和负无穷相加是什么呢?
double abc = -1;
double abc2 = 1;
int in = 0;
double res = abc/0;
double res2 = abc2/0.0;
System.out.println(res);
System.out.println(res2);
System.out.println((res + res2));
System.out.println(abc / in);
结果:NaN
-Infinity
Infinity
NaN
-Infinity
还有定义char类型时单引号中间不能有空格,但是字符串是可以的:
char c = 'a';
char c2 = 'a ';
String s = "a";
String s2 = "a ";