简体   繁体   English

为什么双参数化函数接受浮点数而不是相反?

[英]Why does double parameterised function accepts float and not vice versa?

I have encountered something strange today.我今天遇到了一些奇怪的事情。 The below code compiles unexpectedly and runs fine.下面的代码意外编译并运行良好。

public class Test {

    public static void func(double d) {
        System.out.print("d : " + d);
    }

    public static void main(String[] args) {
        float f = 10.0f;
        func(f); // output: d : 10.0
    }
}

But this one gives compilation error但是这个给出了编译错误

public class Test {

    public static void func(float f) {
        System.out.print("f : " + f);
    }

    public static void main(String[] args) {
        double d = 10.0d;
        func(d);
    }
}

Can somebody please explain this behaviour ?有人可以解释这种行为吗?

Type promotion from float to double is safe as no data is lost and all float 4 bytes can fit into double 8 byes.floatdouble类型提升是安全的,因为不会丢失数据,并且所有float 4 字节都可以放入double 8 字节。

However the opposite, from double to float , always truncates the data as double 8 bytes can't fit into float 4 bytes.然而相反,从doublefloat ,总是截断数据,因为double 8 字节不能适应float 4 字节。 Compiler guards against doing this truncation accidentally by forcing the programmer to manually specify the type conversion.编译器通过强制程序员手动指定类型转换来防止意外进行这种截断。

double (8 byte) is a bigger data type than float (4 byte) so you can store float (4 byte) in double (8 byte) but you can't double in float . double (8 字节)是比float (4 字节)更大的数据类型,因此您可以将float (4 字节)存储在double (8 字节)中,但不能在float double If you try to do that you'll get Possible loss of precision error.如果您尝试这样做,您将获得Possible loss of precision误差Possible loss of precision

So the following will give error.所以下面会报错。

float f = 120.55;

While this one don't虽然这个不

double d = 120.44f;

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

相关问题 为什么选择Float而不是Double? - Why choose Float over Double or vice versa? 为什么int / byte / short / long可以在没有类型转换的情况下转换为float / double,反之亦然 - Why can int/byte/short/long be converted to float/double without typecasting but vice-versa not possible 为什么我需要从double转换为int,反之亦然? - Why do I need to cast from double to int, but not vice versa? 当没有接受long的方法时,为什么java将long参数提升为float / double? - Why does java promote long parameter to float/double when there's no method which accepts long? 如何将float转换为字节数组,反之亦然? - How to convert a float into a byte array and vice versa? Java-将byte []转换为double [],反之亦然 - Java - Convert byte[] to double[] and vice versa 为什么浮点数适合双精度数,但float []不适合双精度数[]? - Why does a float fit in a double but a float[] doesn't fit a double[]? 转换ArrayList <Double> 对于JAVA / Android,双数组,反之亦然 - Converting ArrayList<Double> to Double Array and vice-versa for JAVA/Android 为什么 AutoCloseable 是 Closeable 的基本接口(反之亦然)? - Why is AutoCloseable the base interface for Closeable (and not vice versa)? Java:如何将二进制值的字符串转换为Float,反之亦然? - Java: How to convert a String of Binary values to a Float and vice-versa?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM