Java Float compare()方法及实例

来源:这里教程网 时间:2026-02-17 20:55:17 作者:

Java Float compare()方法及实例

Float类compare() 方法是Java中的一个内置方法,用于比较两个指定的浮点数。返回的整数值的符号与函数调用所返回的整数值的符号相同。

语法

public static int compare(float f1, float f2)

参数: 该函数接受两个参数。

f1 : 第一个要比较的浮点数。f2 : 第二个要比较的浮动值。

返回值: 该函数的返回值如下。

0: 如果f1在数值上等于f2。负值: 如果f1在数值上小于f2。正值: 如果f1在数值上大于f2。

以下程序说明了Float.compare()函数的使用。

程序1: 当两个整数相同时

// Java Program to illustrate// the Float.compare() method import java.lang.Float; public class GFG {    public static void main(String[] args)    {         // Get the two float values        // to be compared        Float f1 = 1023f;        Float f2 = 1023f;         // function call to compare two float values        if (Float.compare(f1, f2) == 0) {             System.out.println("f1=f2");        }        else if (Float.compare(f1, f2) < 0) {             System.out.println("f1<f2");        }        else {             System.out.println("f1>f2");        }    }}

输出

f1=f2

程序2: 当f1<f2

// Java Program to illustrate// the Float.compare() method import java.lang.Float; public class GFG {    public static void main(String[] args)    {         // Get the two float values        // to be compared        Float f1 = 10f;        Float f2 = 1023f;         // function call to compare two float values        if (Float.compare(f1, f2) == 0) {             System.out.println("f1=f2");        }        else if (Float.compare(f1, f2) < 0) {             System.out.println("f1<f2");        }        else {             System.out.println("f1>f2");        }    }}

输出

f1

程序3: 当f1>f2时

// Java Program to illustrate// the Float.compare() method import java.lang.Float; public class GFG {    public static void main(String[] args)    {         // Get the two float values        // to be compared        Float f1 = 1023f;        Float f2 = 10f;         // function call to compare two float values        if (Float.compare(f1, f2) == 0) {             System.out.println("f1=f2");        }        else if (Float.compare(f1, f2) < 0) {             System.out.println("f1<f2");        }        else {             System.out.println("f1>f2");        }    }}

输出

f1>f2

参考 : https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#compare(float, %20float)

相关推荐