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

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

问题描述

我在程序中看到1 / 3.f,想知道.f是什么。所以尝试了我自己的程序:

 #include< iostream> 
using namespace std;
int main()
{
cout<<(float)1/3<< endl;
cout<< 1 / 3.f<<< endl;
cout<< 1/3<< endl;
}

.f是否类似于转换?

解决方案

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



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



免责声明;在上面的解释中使用的cast构造不是一个实际的转换,而只是一种表示文字类型的方法。



如果你想知道所有文字和后缀,你可以阅读C ++标准,( 1997 draft C ++ 11草稿 C ++ 14 draft ),或者看看一本像样的教科书,比如Stroustrup的

另外,在你的例子中(float)1/3 文字 1 3 实际上是整数,但1首先强制转换为float by cast,然后3被隐式转换为float,因为它是一个浮点运算符的右手操作数。 (操作符是浮点,因为它的左边的操作数是浮点。)



编辑:扩展了一些对 .f 并包含指向其他文档的链接。


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

#include<iostream>
using namespace std;
int main()
{
        cout<<(float)1/3<<endl;
        cout<<1/3.f<<endl;
        cout<<1/3<<endl;
}

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

解决方案

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.

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.

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) or alternatively, have a look at a decent textbook, such as Stroustrup's The C++ Programming Language.

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 it's lefthand operand is floating point.)

Edit: expanded a bit on the precise meaning of .f and included the links to further documentation.

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

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