“.f"的目的附加到一个数字? [英] Purpose of a ".f" appended to a number?

查看:19
本文介绍了“.f"的目的附加到一个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个程序中看到 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.)

这篇关于“.f"的目的附加到一个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆