java - Eclipse 中的双精度浮点数与双精度浮点数
问题描述
我的问题分为两部分。
- 为什么以下在 Eclipse 中可以正常工作?“双”不是一堂课吗?
Double h = 2.5;
double j = 2;
- 为什么上面的“Double”在我不为其分配十进制值时会给我一个错误,但“double”无论我是否为其分配一个十进制值都可以?
解决方案
如前所述,该术语是自动装箱。原始类型的对象包装器将自动转换。
至于你的第二部分,
Double a = 2;
不起作用,因为 2 不是双精度数,并且自动装箱仅适用于相同类型。在这种情况下2
是一个 int。
但如果你投它。
Double a = (double)2;
工作得很好。
double a = 2;
之所以有效,是因为 int 可以自动转换为 double。但走另一条路是行不通的。
int a = 2.2; // not permitted.
查看转换部分。在 Java 语言规范中。警告有时可能难以阅读。
修正答案。
在 java 中,您可以向上或向下投射或缩小或扩大投射(从 32 位到 16 位)值正在缩小。但我倾向于认为它是losing vs not losing
一些东西。在大多数情况下,如果您有可能在分配中失去部分价值,则需要进行转换,否则您不需要(参见最后的例外情况)。这里有些例子。
long a = 2; // 2 is an integer but going to a long doesn't `lose` precision.
int b = 2L; // here, 2 is a long and the assignment is not permitted. Even
// though a long 2 will fit inside an int, the cast is still
// required.
int b = (int)2L; // Fine, but clearly a contrived case
浮点数也一样。
float a = 2.2f; // fine
double b = a; // no problem, not precision lost
float c = b; // can't do it, as it requires a cast.
double c = 2.2f; // a float to a double, again a not problem.
float d = 2.2; // 2.2 is a double by default so requires a cast or the float designator.
float d = (float)2.2;
例外
int to float
从or转换时不需要强制转换long to double
。但是,精度仍然会丢失,因为浮点数只有一点24
精度,而双精度数只有一点53
精度。
要查看此内容,ints
您可以运行以下命令:
for (int i = Integer.MAX_VALUE; i > Integer.MAX_VALUE-100; i--) {
float s = i;
int t = (int)s; // normal cast required
if (i != t) {
System.out.println (i + " " + t);
}
}
推荐阅读
- javascript - 让 Jest 与 Babel 7.0.0 一起工作的问题
- java - 在 Java 中查找变量的原始数据类型
- windows - “无法执行‘getImageData’‘CanvasRenderingContext2D’:画布已被跨域数据污染。” 傻瓜
- javascript - React-Chartjs-2:图表上未显示所有数据
- java - 对 ArrayList 进行排序
按创建顺序 [Android/Java] - sql - 未捕获的错误:在“(”附近:在 SQLite 中运行明显正确的语句时出现语法错误
- html - 可编辑跨度从 Edge 中的 DOM 中消失
- angular - Angular APP_INITIALIZER
- dart - 简化可迭代逻辑
- ruby-on-rails - 如何处理 Rails 连接表关系删除?