本文介绍了C 从文字浮点数赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读 关于 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 类型时?

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?

推荐答案

您示例中的浮点数组初始化在 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"一词的意思是两次,不是指同名的类型).如果按如下方式初始化 f1f2,它们最终会得到不同的值,而 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 从文字浮点数赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:56