java - 在 Java 中表示浮点值

标签 java floating-point

请看下面的三行代码。

  float f = 1;

  float g = 1.1;

  float h = 1.1f;

第二行有编译错误,其他行没有编译错误。第一行在没有后缀 f 的情况下工作正常,第三行在使用后缀 f 的情况下工作。这是为什么?

最佳答案

默认情况下,Java 中的浮点文字是一个 double 值。

JLS 3.10.2 Floating-Point Literals

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d.

如果没有显式收缩转换,您不能将 double 值分配给 float。因此,您有两个选择:

  • 对于文字,使用后缀fF 来表示float
  • 对于非文字,使用显式转换 (float)

后者的一个例子是:

double d = 1.1;
float f = (float) d; // compiles fine!

关于扩大转化

编译的原因:

float f = 1;

是因为从 intfloat 的扩展转换可以在赋值上下文中隐式完成。

JLS 5.2 Assignment Conversion

Assignment conversion occurs when the value of an expression is assigned to a variable: the type of the expression must be converted to the type of the variable. Assignment contexts allow the use of one of the following:

  • a widening primitive conversion (§5.1.2)
  • [...]

JLS 5.1.2 Widening Primitive Conversion

The following 19 specific conversions on primitive types are called the widening primitive conversions:

  • int to long, float, or double
  • [...]

文字的其他数据类型后缀

如上所述,double 也有 Dd 后缀。例如考虑这个片段:

static void f(int i) {
    System.out.println("(int)");
}
static void f(double d) {
    System.out.println("(double)");
}

//...
f(1);   // prints "(int)"
f(1D);  // prints "(double)"

long 文字还有一个后缀,即Ll(小写字母)。 强烈建议您使用大写变体。

JLS 3.10.1 Integer Literals

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int. The suffix L is preferred, because the letter l (ell) is often hard to distinguish from the digit 1 (one).

关于java - 在 Java 中表示浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3033137/

相关文章:

java - 如何使用 Java 连接到基于 Web 的 Oracle 数据库?

java - Android:登录的后台进程

floating-point - 如何在 Haxe 中可靠地将 float 格式化为指定的小数位数

java - 发送带有附件的邮件的最佳策略,并且 JVM 内存占用较低

java - 具有 2 个用户角色的 tomcat 上的 j_security_check

java - 如何在 java 中测试匿名嵌套类?

c++ - 为什么这个 SOR 求解器的速度取决于输入?

python - 如何显示带有两位小数的 float ?

ios - 增加或减少 float

math - float 学有问题吗?