C语言中的浮点常量

3

我有一个关于C语言浮点常量的问题。

在Java中,浮点数常量的默认类型是double,因此以下代码将导致编译错误:

float f = 100.0;   // we either need to uses type case operator or put f at the end of the number constant.

这是因为默认的浮点常量类型为double,而在没有类型转换运算符的情况下从double向float进行强制转换是错误的,所以我们需要添加类型转换运算符或在数字末尾加上f。

那么,在C语言中为什么不会产生错误呢?是因为默认的浮点常量类型为float,还是因为编译器进行了隐式的向下转换(在C语言中不需要类型转换运算符)?

3个回答

8

C语言中,默认情况下,浮点常量的类型为double,但是double可以隐式转换为float(注意,如果常量的值超出了float可表示的范围,则执行此类转换的结果未定义,请小心)。

如果你想要一个float类型的浮点常量,你可以在常量末尾添加后缀f


4
未标识类型的浮点常量在C语言中也是双精度。详见标准§6.4.4.2:链接
你是正确的,这里发生了窄化:
§6:3.1.5:
"When a double is demoted to float, a long double is demoted to double or float, or a value being represented in greater precision and range than required by its semantic type (see 6.3.1.8) is explicitly converted to its semantic type, if the value being converted can be represented exactly in the new type, it is unchanged. If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner. If the value being converted is outside the range of values that can be represented, the behavior is undefined."
§6:5.16:
"The type of an assignment expression is the type of the left operand [...]."
§6:5.16.1:
"In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand."

2

C语言会将 double 强制转换为 float。另外,浮点型字面量被默认为 double

gcc 中,编译器选项 -Wconversion (在 -Wall 中没有附带)会对这种降级操作进行警告(例如在文字赋值中,就像你的问题所示)。

警告:从 'double' 转换到 'float' 可能会改变其值


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接