Why is the “f” required when declaring floats?

前端 未结 3 1488
暖寄归人
暖寄归人 2020-11-27 03:01

Example:

float timeRemaining = 0.58f;

Why is the f is required at the end of this number?

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 03:16

    Because there are several numeric types that the compiler can use to represent the value 0.58: float, double and decimal. Unless you are OK with the compiler picking one for you, you have to disambiguate.

    The documentation for double states that if you do not specify the type yourself the compiler always picks double as the type of any real numeric literal:

    By default, a real numeric literal on the right side of the assignment operator is treated as double. However, if you want an integer number to be treated as double, use the suffix d or D.

    Appending the suffix f creates a float; the suffix d creates a double; the suffix m creates a decimal. All of these also work in uppercase.

    However, this is still not enough to explain why this does not compile:

    float timeRemaining = 0.58;
    

    The missing half of the answer is that the conversion from the double 0.58 to the float timeRemaining potentially loses information, so the compiler refuses to apply it implicitly. If you add an explicit cast the conversion is performed; if you add the f suffix then no conversion will be needed. In both cases the code would then compile.

提交回复
热议问题