在 Java 中使用后缀 F

Sheeraz Gul 2023年10月12日
在 Java 中使用后缀 F

Java 中的十进制值默认是 double 值。当我们只需要浮点值时,我们必须告诉编译器它是一个浮点值。

本教程演示了 Java 中后缀 f 的使用。

在 Java 中使用 f 来告诉编译器它是一个浮点值

为此,我们在值之后使用后缀 f。带有后缀 f 的值将被编译器识别为浮点数。

一旦我们在 Java 中定义了变量,我们必须指定该变量的数据类型,但如果浮点数没有预定义,我们可以使用后缀 f 告诉编译器它是一个浮点值。

例子:

public class Java_F {
  public static void main(String args[]) {
    float num1 = 5.5f;
    double num2 = 5f;

    // Check the type of the variables above
    System.out.println("The Data Types for the values are: ");
    System.out.println(((Object) num1).getClass().getSimpleName() + " = " + num1);
    System.out.println(((Object) num2).getClass().getSimpleName() + " = " + num2);
    System.out.println(((Object) 5f).getClass().getSimpleName() + " = " + 5f);
  }
}

输出:

The Data Types for the values are:
Float = 5.5
Double = 5.0
Float = 5.0

上面的代码使用带有预定义变量和未定义值的 f。此示例检查给定值的数据类型。

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相关文章 - Java Data Type