“.f"的目的附加到一个数字?

2021-12-31 00:00:00 syntax casting c++

我在一个程序中看到 1/3.f 并想知道 .f 是做什么用的.所以尝试了我自己的程序:

I saw 1/3.f in a program and wondered what the .f was for. So tried my own program:

#include <iostream>

int main()
{
    std::cout << (float) 1/3 << std::endl;
    std::cout << 1/3.f << std::endl;
    std::cout << 1/3 << std::endl;
}

.f 是否像演员表一样使用?有什么地方可以让我详细了解这种有趣的语法吗?

Is the .f used like a cast? Is there a place where I can read more about this interesting syntax?

推荐答案

没有 .f 数字被解释为整数,因此 1/3(int)1/(int)3 => (int)0 而不是所需的 (float)0.333333..f 告诉编译器将文字解释为 float 类型的浮点数.还有其他这样的结构,例如 0UL 表示 (unsigned long)0,而普通的 0 将是 (int)0.

Without the .f the number gets interpreted as an integer, hence 1/3 is (int)1/(int)3 => (int)0 instead of the desired (float)0.333333. The .f tells the compiler to interpret the literal as a floating point number of type float. There are other such constructs such as for example 0UL which means a (unsigned long)0, whereas a plain 0 would be an (int)0.

.f 实际上是两个组件,. 表示文字是浮点数而不是整数,fcode> 后缀,它告诉编译器文字应该是 float 类型,而不是用于浮点文字的默认 double 类型.

The .f is actually two components, the . which indicates that the literal is a floating point number rather than an integer, and the f suffix which tells the compiler the literal should be of type float rather than the default double type used for floating point literals.

免责声明;上面解释中使用的强制转换结构"并不是实际的强制转换,而只是表示文字类型的一种方式.

Disclaimer; the "cast construct" used in the above explanation is not an actual cast, but just a way to indicate the type of the literal.

如果你想知道所有关于文字和你可以在其中使用的后缀,你可以阅读 C++ 标准,(1997 年草案,C++11 草案,C++14 草案,C++17 草案) 或者,看看一本像样的教科书,例如 Stroustrup 的 C++ 编程语言.

If you want to know all about literals and the suffixes you can use in them, you can read the C++ standard, (1997 draft, C++11 draft, C++14 draft, C++17 draft) or alternatively, have a look at a decent textbook, such as Stroustrup's The C++ Programming Language.

顺便说一句,在您的示例 (float)1/3 中,文字 13 实际上是整数,但 1 是首先由您的演员转换为浮点数,然后 3 隐式转换为浮点数,因为它是浮点运算符的右侧操作数.(运算符是浮点数,因为它的左手操作数是浮点数.)

As an aside, in your example (float)1/3 the literals 1 and 3 are actually integers, but the 1 is first cast to a float by your cast, then subsequently the 3 gets implicitly cast to a float because it is a righthand operand of a floating point operator. (The operator is floating point because its lefthand operand is floating point.)

相关文章