为什么在声明浮点数时需要“f”?(Why is the “f” required when declaring floats?)

编程入门 行业动态 更新时间:2024-10-26 21:31:47
为什么在声明浮点数时需要“f”?(Why is the “f” required when declaring floats?)

例:

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;

更多推荐

本文发布于:2023-08-04 15:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1417883.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时需   声明   浮点数   floats   required

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!