Java: double vs float

后端 未结 6 1198
一整个雨季
一整个雨季 2020-12-09 16:37

In another Bruce Eckel exercise, the code I\'ve written takes a method and changes value in another class. Here is my code:

class Big {
  float b;
}

public         


        
6条回答
  •  一生所求
    2020-12-09 17:04

    By default, Java will treat a decimal (e.g. "4.3") as a double unless you otherwise specify a float by adding an f after the number (e.g. "4.3f").

    You're having the same problem on both lines. First, the decimal literal is interpreted as a double by the compiler. It then attempts to assign it to b, which is of type float. Since a double is 64 bits and a float is only 32 bits (see Java's primitives documentation), Java gives you an error indicating that the float cannot fit inside the double. The solution is to add an f to your decimal literals.

    If you were trying to do the opposite (i.e. assign a float to a double), that would be okay since you can fit a float's 32 bits within a double's 64.

提交回复
热议问题