Java 数字文字末尾的 F 和 D 是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4331200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:58:56  来源:igfitidea点击:

What do F and D mean at the end of numeric literals?

javafloating-pointdouble

提问by Ben C.

I've seen some of this symbols, but I cannot find anything strange with it,

我见过一些这样的符号,但我找不到任何奇怪的地方,

double d = 5D;
float f = 3.0F;

What does the D and F behind 5 exactly means?

5 后面的 D 和 F 到底是什么意思?

采纳答案by EboMike

Means that these numbers are doubles and floats, respectively. Assume you have

意味着这些数字分别是双精度数和浮点数。假设你有

void foo(int x);
void foo(float x);
void foo(double x);

and then you call

然后你打电话

foo(5)

the compiler might be stumped. That's why you can say 5, 5f, or 5.0to specify the type.

编译器可能会被难住。这就是为什么您可以说5, 5f, 或5.0来指定类型。

回答by Joshua Martell

It defines the datatype for the constants 5 and 3.0.

它定义了常量 5 和 3.0 的数据类型。

回答by Ronnie Howell

D stands for double and F stands for float. You will occasionally need to add these modifiers, as 5 is considered an integer in this case, and 3.0 is a double.

D 代表双精度,F 代表浮点数。您偶尔需要添加这些修饰符,因为在这种情况下 5 被视为整数,而 3.0 是双精度数。

回答by Jeff

They're format specifiers for float and double literals. When you write 1.0, it's ambiguous as to whether you intend the literal to be a float or double. By writing 1.0f, you're telling Java that you intend the literal to be a float, while using 1.0dspecifies that it should be a double. There's also L, which represents long (e.g., 1Lis a long1, as opposed to an int1)

它们是 float 和 double 文字的格式说明符。当您编写 时1.0,不清楚您希望文字是浮点数还是双精度数。通过编写1.0f,您告诉Java 您打算将文字作为浮点数,而使用1.0d指定它应该是双精度数。还有L, 代表长(例如,1Llong1,而不是int1)

回答by Jason Rogers

D stands for double

D 代表双

F for float

F 为浮点数

you can read up on the basic primitive types of java here

您可以在此处阅读 Java 的基本原始类型

http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

I would like to point out that writing

我想指出写作

5.1D or 5.1 : if you don't specify a type letter for a comma number then by default it is double

5.1D 或 5.1 :如果您没有为逗号数字指定类型字母,那么默认情况下它是双精度

5 : without the period, by default it is an int

5 : 没有句点,默认是一个int

回答by Theresa Forster

As others have mentioned they are the Type definitions, however you will less likely see i or d mentioned as these are the defaults.

正如其他人所提到的,它们是类型定义,但是您不太可能看到 i 或 d 被提及,因为这些是默认值。

float myfloat = 0.5; 

will error as the 0.5 is a double as default and you cannot autobox down from double to float (64 -> 32 bits) but

会出错,因为 0.5 是默认的双精度值,您不能从双精度自动装箱为浮点数(64 -> 32 位),但是

double mydouble = 0.5;

will have no problem

不会有问题