为什么在浮点数末尾使用字母f? [英] Why is the letter f used at the end of a float no.?
问题描述
我只想了解一些相关信息。
I just wanted some information about this.
float n = 2.99944323200023f
文字末尾的 f
是什么?这叫什么?为什么使用?
What does the f
at the end of the literal do? What is it called? Why is it used?
推荐答案
f
表示它是浮点数文字,而不是双字面(它本来就是隐含的。)它没有我所知道的特定技术名称 - 如果我需要专门提及它,我倾向于将其称为字母后缀,尽管这是有点武断!
The f
indicates it's a floating point literal, not a double literal (which it would implicitly be otherwise.) It hasn't got a particular technical name that I know of - I tend to call it the "letter suffix" if I need to refer to it specifically, though that's somewhat arbitrary!
例如:
float f = 3.14f; //Compiles
float f = 3.14; //Doesn't compile, because you're trying to put a double literal in a float without a cast.
您当然可以这样做:
float f = (float)3.14;
...它完成了近乎相同的事情,但F是一个更整洁,更简洁的方式显示它。
...which accomplishes near enough the same thing, but the F is a neater, more concise way of showing it.
为什么选择双重作为默认而不是浮动?好吧,现在99%的情况下浮点数的双倍内存要求不是问题,并且它们提供的额外准确性在很多情况下都是有益的 - 所以你可以说这是合理的默认值。
Why was double chosen as the default rather than float? Well, these days the memory requirements of a double over a float aren't an issue in 99% of cases, and the extra accuracy they provide is beneficial in a lot of cases - so you could argue that's the sensible default.
请注意,您可以通过在结尾处放置 d
来明确地将十进制文字显示为double:
Note that you can explicitly show a decimal literal as a double by putting a d
at the end also:
double d = 3.14d;
...但是因为它无论如何都是双倍值,所以没有效果。有些人可能会主张它提倡它更清楚你的意思是什么字面类型,但我个人觉得它只是杂乱的代码(除非你有很多浮动文字,你要强调这个文字确实意味着一个双重,遗漏f不仅仅是一个错误。)
...but because it's a double value anyway, this has no effect. Some people might argue for it advocating it's clearer what literal type you mean, but personally I think it just clutters code (unless perhaps you have a lot of float literals hanging around and you want to emphasise that this literal is indeed meant to be a double, and the omission of the f isn't just a bug.)
这篇关于为什么在浮点数末尾使用字母f?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!