简体   繁体   English

当一个数字在 Java 中被认为是双精度时,为什么我们使用浮点数?

[英]Why we use float when a number is considered as double in Java?

Why we use float type to store a number eg 1.23 when it's considered as double?.为什么我们使用浮点类型来存储一个数字,例如 1.23 当它被认为是双精度? If we have to store 1.23 as float we type :如果我们必须将 1.23 存储为浮点数,我们键入:

float number = 1.23F;

Why we use 'F' when float type is used?为什么我们在使用浮点类型时使用'F'?

Here is a great explanation from " Learning Java ":这是“ 学习Java ”的一个很好的解释:

Floating-point literals are of type double unless they are suffixed with an f or F denoting that they are to be produced as a float value.浮点字面量是 double 类型,除非它们以 f 或 F 后缀表示它们将作为浮点值生成。

Besides that, here are the similarities and the differences between these two primitive types.除此之外,这里是这两种原始类型之间的相似之处和不同之处。

  • Both float and double consider float-point numbers. floatdouble都考虑浮点数。

  • The difference is the precision each of them gives you.不同之处在于它们每个给您的精度。 Whereas the float type can give you "only" 6-7 significant decimal digits, the double goes as far as having 15. As Mirek commented, the memory they need is different as well - 4 and 8 bytes accordingly.虽然float类型可以“仅”为您提供 6-7 个有效十进制数字,但double可以达到 15 个。正如Mirek评论的那样,它们所需的内存也不同 - 相应的 4 和 8 个字节。

Hope this clears up the confusion!希望这能消除混乱!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM