Difference between Math.Floor() and Math.Truncate()
.NET中
为了完整起见,
另请参阅:Pax Diablo的答案。强烈推荐!
请通过以下链接获取有关以下内容的MSDN描述:
-
Math.Floor ,向下舍入为负无穷大。 -
Math.Ceiling ,向上取整为正无穷大。 -
Math.Truncate ,向上或向下舍入为零。 -
Math.Round ,四舍五入到最接近的整数或指定的小数位数。您可以指定行为是否在两种可能性之间完全等距,例如四舍五入以使最终数字为偶数("Round(2.5,MidpointRounding.ToEven) "变为2)或使其远离零("Round(2.5,MidpointRounding.AwayFromZero) "变为3)。
以下图表和表格可能会有所帮助:
1 2 3 4 5 6 7 8 9 10 11 | -3 -2 -1 0 1 2 3 +--|------+---------+----|----+--|------+----|----+-------|-+ a b c d e a=-2.7 b=-0.5 c=0.3 d=1.5 e=2.8 ====== ====== ===== ===== ===== Floor -3 -1 0 1 2 Ceiling -2 0 1 2 3 Truncate -2 0 0 1 2 Round (ToEven) -3 0 0 2 3 Round (AwayFromZero) -3 -1 0 2 3 |
请注意,
1 2 3 | n = 3.145; a = System.Math.Round (n, 2, MidpointRounding.ToEven); // 3.14 b = System.Math.Round (n, 2, MidpointRounding.AwayFromZero); // 3.15 |
对于其他功能,您必须使用乘/除技巧才能达到相同的效果:
1 2 | c = System.Math.Truncate (n * 100) / 100; // 3.14 d = System.Math.Ceiling (n * 100) / 100; // 3.15 |
例如:
1 2 | Math.Floor(-3.4) = -4 Math.Truncate(-3.4) = -3 |
而
1 2 | Math.Floor(3.4) = 3 Math.Truncate(3.4) = 3 |
一些例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Round(1.5) = 2 Round(2.5) = 2 Round(1.5, MidpointRounding.AwayFromZero) = 2 Round(2.5, MidpointRounding.AwayFromZero) = 3 Round(1.55, 1) = 1.6 Round(1.65, 1) = 1.6 Round(1.55, 1, MidpointRounding.AwayFromZero) = 1.6 Round(1.65, 1, MidpointRounding.AwayFromZero) = 1.7 Truncate(2.10) = 2 Truncate(2.00) = 2 Truncate(1.90) = 1 Truncate(1.80) = 1 |
它们在功能上等同于正数。不同之处在于它们处理负数的方式。
例如:
1 2 3 4 5 | Math.Floor(2.5) = 2 Math.Truncate(2.5) = 2 Math.Floor(-2.5) = -3 Math.Truncate(-2.5) = -2 |
MSDN链接:
-数学地板方法
-Math.Truncate方法
附:当心Math.Round可能不是您期望的那样。
要获得"标准"舍入结果,请使用:
1 2 3 4 | float myFloat = 4.5; Console.WriteLine( Math.Round(myFloat) ); // writes 4 Console.WriteLine( Math.Round(myFloat, 0, MidpointRounding.AwayFromZero) ) //writes 5 Console.WriteLine( myFloat.ToString("F0") ); // writes 5 |
符合IEEE 754标准第4部分的"向负无穷大"。
返回小于或等于指定数字的最大整数。
MSDN system.math.floor
计算数字的整数部分。
MSDN system.math.truncate
1 2 3 4 5 6 7 8 9 10 | Math.Floor(2.56) = 2 Math.Floor(3.22) = 3 Math.Floor(-2.56) = -3 Math.Floor(-3.26) = -4 Math.Truncate(2.56) = 2 Math.Truncate(2.00) = 2 Math.Truncate(1.20) = 1 Math.Truncate(-3.26) = -3 Math.Truncate(-3.96) = -3 |
另外Math.Round()
1 2 3 4 5 | Math.Round(1.6) = 2 Math.Round(-8.56) = -9 Math.Round(8.16) = 8 Math.Round(8.50) = 8 Math.Round(8.51) = 9 |
我们去上班吧! (?□_□)
在左侧...
现在就把它拿回来...
这次是两跳...
大家都拍拍手吗?
你能走多低?你能走低吗?一直到
1 2 | if (this =="wrong") return"i don't wanna be right"; |
通过删除正或负分数,您总是朝着0前进。