简体   繁体   English

浮点到整数vs整数到浮点自动转换

[英]Float to Int vs Int to Float automatic conversion

I'm studying java by Herbert Schildt's "Java for beginners" book. 我正在通过Herbert Schildt的“面向初学者的Java”书来学习Java。 It is said that, being a destiny variable compatible and sufficiently big to store an origin one, an automatic conversion is done. 可以说,由于命运变量是兼容的并且足够大以存储原始变量,因此可以进行自动转换。

That being said, an Int should be able to store an Float and vice-versa, since they both have a 4 bytes size. 就是说,一个Int应该能够存储Float,反之亦然,因为它们都具有4个字节的大小。

public class MyClass {
    public static void main(String args[]) {
        int i = 10;
        float f = i;

        float ff = 10;
        int ii = ff; 
    }
}

However, when compiled, this piece of code generetes the following error: 但是,这段代码在编译时会产生以下错误:

/MyClass.java:15: error: incompatible types: possible lossy conversion from float to int
        int ii = ff; 
                 ^
1 error

Why is there that, being a compatible type and sufficiently big to store each other, a float can store an int but an int cannot store a float? 为什么是一个兼容类型并且足够大以相互存储的浮点数可以存储一个int,而一个int不能存储一个浮点呢?

Because float contains numbers also after the decimal point and int does not. 因为float还在小数点后也包含数字,而int不包含数字。 Without this you shouldn't be able to simply trim the decimal part from the number by explicitly casting the float to int too. 没有这个,您也不能通过将浮点数也显式转换为int来简单地修剪数字的小数部分。

As you can see, you can store a int into a float , but you can't put a float inside a int . 如您所见,您可以将int存储到float ,但是不能将float放入int

This heappens because the internal structure of float is a decimal number and int, as its name says, is integer. 这是因为float的内部结构是一个十进制数,而int顾名思义是整数。

For more information you can take a look into this discussion about How are floating point numbers are stored in memory . 有关更多信息,您可以查看有关如何将浮点数存储在内存中的讨论

an Int should be able to store an Float and vice-versa, since they both have a 4 bytes size. 一个Int应该能够存储Float,反之亦然,因为它们都具有4个字节的大小。

The size of the data is not the important part. 数据的大小不是重要的部分。 Rather it is about the values which can be stored in the give number of bytes. 而是关于可以存储在给定字节数中的值。 int can only store whole number values between -2^31 and 2^31-1. int只能存储-2 ^ 31和2 ^ 31-1之间的整数值。 On the other hand, float can store decimal values. 另一方面, float可以存储十进制值。

Int to float is never a lossy conversion if the integer value will be within the range of maximum integer value that float can store as value will always be stored/converted to <intvalue>.0 like 4 will be stored as 4.0 . 如果整数值将在float可以存储的最大整数值的范围内,则int到float永远不会是有损转换,因为float值将始终存储/转换为<intvalue>.0例如4将被存储为4.0 But in case of conversion from float to int, your fraction value will be lost so JVM gives you such error. 但是,如果从float转换为int,您的分数值将丢失,因此JVM会给您此类错误。 If you can take such risk then you have to explicitly convert the float value into int. 如果冒这样的风险,则必须将float值显式转换为int。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM