重载函数抛出浮点参数错误

Overloaded function throws an error for float arguments

这是我的Java程序代码。我为数据类型 intfloat 重载了 add 函数,但是调用 add(2.3, 2.4) 抛出错误,而不是调用 add(float, float).

public class Main {

    public static void main(String[] args) {

        // This calls add(int, int) as expected
        System.out.println(add(2,4));

        // This call throws an error
        System.out.println(add(2.3,3.4));

    }

    public static int add(int a, int b){
        return (a + b);
    }

    public static float add(float a, float b){
        return (a + b);
    }

}

intfloatadd 个方法,而文字 2.3 的类型为 double。有两种方法可以解决此问题:

  1. 使用 float 文字,即 2.3f3.4f(注意 f 后缀)。

  2. double 定义 add 方法。

您正确定义了重载方法!

你错的是你调用方法的方式。您正在呼叫 add(2.3,3.4)2.33.4都是double。这就是为什么不能将它们直接放入接受浮点数的方法中的原因。

"What? Why are they doubles?"你可能会问。

默认情况下,所有没有 .e 的数字文字都被认为是 int。并且所有具有 .e 之一或两者的数字文字都被认为是 doubles.

要创建浮点文字,请将 f 添加到数字的末尾。即这些都是浮点数:

1f
1000f
1.1f
-9f
1e99f

所以你应该这样调用你的方法

add(2.3f,3.4f)