来自文字的C浮点赋值 [英] C float assignment from literal
问题描述
在阅读关于3D图形的书我遇到了以下任务:
While reading part of a book about 3D graphics I came across the following assignment:
const float vertexPositions[] = {
0.75f, 0.75f, 0.0f, 1.0f,
0.75f, -0.75f, 0.0f, 1.0f,
-0.75f, -0.75f, 0.0f, 1.0f,
};
为什么后缀f是必需的?是否可以根据变量的类型来确定文字的类型?我相信没有f float字面量会被解释为双精度,但是为什么当数组明显是float类型的时候呢?
Why is the f suffix necessary? Can the type of the literals not be determined from the type of the variable? I believe that without the f float literals are interpreted as doubles, but why when the array is clearly of type float?
推荐答案
示例中的float数组初始化在C语言中很好,就像使用double
常量一样.对于手头的值,如果它是用float
常量初始化的double
数组,也可以,因为手头的值可以精确地表示为float
.即使在这最后一种情况下,编译器也没有理由发出警告,尽管这很奇怪并使开发人员费心键入其他与最终类型不匹配的后缀.
The float array initialization in your example is fine in C, as it would be if it used double
constants. For the values at hand, it would also be fine if it were a double
array initialized with float
constants, because the values at hand are exactly representable as float
. There would be no reason for a compiler to emit a warning even in this last case, although it would be strange and confusing that the developer bothered to type additional suffixes that do not match the eventual type.
简而言之,作者只是明确的,对于float
数组,这是很好的.
In short, the author is only being explicit, which, in the case of a float
array, is good.
对于以十进制表示的任意值,由于double常量初始化float
变量. "nofollow>双取整" (其中"double"一词表示两次,并且不表示相同名称的类型).如果按以下方式初始化f1
和f2
,它们最终将具有不同的值,并且f1
实际上是最接近预期值1.01161128282547的
For arbitrary values written in decimal, you do not want to initialize float
variables with double
constants because of "double-rounding" (in which the word "double" means twice and does not refer to the type of the same name). If you initialize f1
and f2
as follows, they end up with different values, and f1
is actually the closest to the intended value 1.01161128282547:
float f1 = 1.01161128282547f;
float f2 = 1.01161128282547;
原因在于,对于f2
,十进制值为1.01161128282547 首先四舍五入到最近的double
,然后四舍五入到最近的float
.与直接四舍五入到最近的float
(初始化f1
的方式)相比,这两个步骤引入了更多的错误.
The explanation is that in the case of f2
, the decimal value 1.01161128282547 is first rounded to the nearest double
, and then to the nearest float
. These two steps introduce more error than directly rounding to the nearest float
, which is how f1
is initialized.
这篇关于来自文字的C浮点赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!