我在一个程序中看到 1/3.f
并想知道 .f
是干什么用的。所以尝试了我自己的程序:
#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
是否像演员表一样使用?有没有地方可以让我了解更多关于这种有趣语法的信息?
原文由 Nav 发布,翻译遵循 CC BY-SA 4.0 许可协议
Without the
.f
the number gets interpreted as an integer, hence1/3
is(int)1/(int)3
=>(int)0
instead of the desired(float)0.333333
..f
告诉编译器将文字解释为浮点类型的浮点数。 There are other such constructs such as for example0UL
which means a(unsigned long)0
, whereas a plain0
would be an(int)0
..f
实际上是两个组件,.
表示字面量是浮点数而不是整数,f
后缀告诉编译器文字应该是浮点类型,而不是用于浮点文字的默认双精度类型。免责声明;上述解释中使用的“强制转换构造”不是实际的强制转换,而只是表示文字类型的一种方式。
如果您想了解有关文字和可以在其中使用的后缀的所有信息,您可以阅读 C++ 标准( 1997 草案、 C++11 草案、 C++14 草案、 C++17 草案)或者,看一本像样的教科书,例如 Stroustrup 的 The C++ Programming Language 。
顺便说一句,在您的示例中
(float)1/3
文字1
和3
实际上是整数,但是 1 首先由您的演员转换为浮点数,然后3 被隐式转换为浮点数,因为它是浮点运算符的右手操作数。 (运算符是浮点数,因为它的左操作数是浮点数。)