0

I was bit curious that why we use trailing character in Java/C++. Like,

float f = 23f;

we can also write

float f = 23;

both having same effect.

4

3 回答 3

6

当您在数学运算中对数字进行硬编码时,这一点很重要。

例如:

5 / 2 == 2
5.0f / 2.0f = 2.5f
5.0 / 2.0 = 2.5      // without the 'f' suffix you have doubles
5.0d / 2.0d = 2.5d   // for doubles 'd' can be used as well

这些也会有不同的结果:

blah / 3.141592653592  // this returns an accurate double
blah / 3.141592653592f // this returns a less accurate float
于 2013-06-22T11:37:04.253 回答
1

This is because there is something else that can supply the type information in the second case (namely, the type of the variable). In cases like that suffixes are not required.

However, you may need them in other cases, when the type information must be derived from the numeric literal itself. For example, consider the two expressions below:

float f = 23 / 5;  // Integer division

vs.

float f = 23f / 5; // Floating point division

You would get different results with and without the suffix.

于 2013-06-22T11:39:29.690 回答
0

它们具有相同的效果,但第二步中多了一个步骤。的数据类型23int。编译器几乎肯定会23在编译时转换为浮点数,但它必须检查数字是否可以表示为浮点数。它们占用相同数量的空间,因此某些整数不能表示为浮点数。考虑以下 Java 代码:

int i   = 2147483647; // Integer.MAX_VALUE, but at compile time.
System.out.println(i);

float f = 2147483647; // Integer.MAX_VALUE, but at compile time.
System.out.println(f);

打印什么?

于 2013-06-22T11:45:53.087 回答