问题很简单,有什么好处或区别吗?我注意到在 C# 中,该函数返回一个没有任何小数位的 double ,而在 Java 中它保留小数位,但除此之外结果是相同的。
这是我在 Java 和 C# 中使用的代码,以及输出:
//Java //C#
double a = 5.5; double a = 5.5;
System.out.println(Math.floor(a)); Console.WriteLine(Math.Floor(a));
System.out.println((int)a); Console.WriteLine((int)a);
//Output //Output
5.0 5
5 5
是,对于负数,这是相反的。
示例(使用 Mono 的 C# 交互式 shell csharp
):
csharp> Math.Floor(-12.0d)
-12
csharp> Math.Floor(-12.5d)
-13
csharp> (int) -12.5
-12
(对于 Java/C# 都相同)而且我猜大多数语言都是如此。
转换一个 float 为一个整数,是通过丢弃保留整数部分的小数部分来执行的。 -12.5
的整数部分是12
。因此,如果将负数转换为 int
,则执行 Math.Ceil
。
此外,正如@Matthew 所说,float
或 double
可以达到 1.023e23
(Avogadro 常数)。仅仅是因为 mantisse 不能再代表逗号后面的数字了。 被认为是整数的数字,但不能用 int
表示。通过执行 Math.floor
操作,什么也没有发生,但值仍然保持不变。虽然转换为 int
可能会导致溢出:
示例:
csharp> double ac = 1.023e23;
csharp> Math.Floor(ac);
1.023E+23
csharp> (int) ac;
0
Note: this may look far fetched, but there is thus a clear difference in semantics nevertheless. A difference that tends to lead to errors anyway.
此外,它works differently对于无限 数字和NaN :
System.out.println(Math.floor(Double.POSITIVE_INFINITY)); // Prints Infinity
System.out.println((int)Double.POSITIVE_INFINITY); // Prints 2147483647
System.out.println(Math.floor(Double.NaN)); // Prints NaN
System.out.println((int)Double.NaN); // Prints 0
但我还是会一直使用它们。类型转换让事情变得更加不可读。四舍五入更多是 Actor 的某种(副作用)。通过使用 Math.Ceil/Floor/Round
,您的意思很清楚。
有时转换为整数确实比先执行 floor/ceil 操作更有效。但是聪明的编译器有时可以推断出一个变量将始终存储一个正数,从而对其进行优化。此外,对于大多数应用程序,这将导致微不足道的性能损失。