例:
float timeRemaining = 0.58f;为什么在数字结尾需要f ?
Example:
float timeRemaining = 0.58f;Why is the f is required at the end of the number?
最满意答案
您的浮动声明包含两部分:
它声明变量timeRemaining是float类型。 它为此变量赋值0.58 。问题发生在第2部分。
右侧是自行评估的。 根据C#规范,包含没有后缀的小数点的数字被解释为double 。
所以我们现在有一个double值,我们要赋值给float类型的变量。 为了做到这一点,必须有从double到float的隐式转换。 没有这样的转换,因为您可能(在这种情况下)会丢失转化中的信息。
原因是编译器使用的值不是真的为0.58,而是最接近0.58的浮点值,这是0.57999999999999978655962351581366 ...的double ,正好为0.579999946057796478271484375。
严格来说,不需要f 。 您可以避免使用f后缀通过将值转换为float :
float timeRemaining = (float)0.58;Your declaration of a float contains two parts:
It declares that the variable timeRemaining is of type float. It assigns the value 0.58 to this variable.The problem occurs in part 2.
The right-hand side is evaluated on its own. According to the C# specification, a number containing a decimal point that doesn't have a suffix is interpreted as a double.
So we now have a double value that we want to assign to a variable of type float. In order to do this, there must be an implicit conversion from double to float. There is no such conversion, because you may (and in this case do) lose information in the conversion.
The reason is that the value used by the compiler isn't really 0.58, but the floating-point value closest to 0.58, which is 0.57999999999999978655962351581366... for double and exactly 0.579999946057796478271484375 for float.
Strictly speaking, the f is not required. You can avoid having to use the f suffix by casting the value to a float:
float timeRemaining = (float)0.58;更多推荐
发布评论