题
有什么区别 Math.Floor()
和 Math.Truncate()
在.NET 中?
没有正确的解决方案
其他提示
Math.Floor
向下舍入, Math.Ceiling
四舍五入,并且 Math.Truncate
向零舍入。因此, Math.Truncate
就好像 Math.Floor
对于正数,比如 Math.Ceiling
对于负数。这是 参考.
为了完整性, Math.Round
四舍五入到最接近的整数。如果该数字恰好位于两个整数之间,则向偶数舍入。 参考。
也可以看看: 帕克斯·迪亚波罗的回答. 。强烈推荐!
请点击以下链接获取 MSDN 描述:
Math.Floor
, ,向下舍入到负无穷大。Math.Ceiling
, ,向上舍入为正无穷大。Math.Truncate
, ,向上或向下舍入为零。Math.Round
, ,四舍五入到最接近的整数或指定的小数位数。如果两种可能性之间的距离完全相等,您可以指定行为,例如四舍五入以使最终数字为偶数 ("Round(2.5,MidpointRounding.ToEven)
“ 变为 2) 左右,使其远离零 (“Round(2.5,MidpointRounding.AwayFromZero)
” 变成 3)。
下面的图表可能会有所帮助:
-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
注意 Round
比看起来强大得多,只是因为它可以四舍五入到特定的小数位数。所有其他的始终四舍五入到零小数。例如:
n = 3.145;
a = System.Math.Round (n, 2, MidpointRounding.ToEven); // 3.14
b = System.Math.Round (n, 2, MidpointRounding.AwayFromZero); // 3.15
对于其他函数,您必须使用乘法/除法技巧才能达到相同的效果:
c = System.Math.Truncate (n * 100) / 100; // 3.14
d = System.Math.Ceiling (n * 100) / 100; // 3.15
Math.Floor()
向负无穷大舍入
Math.Truncate
向零向上或向下舍入。
例如:
Math.Floor(-3.4) = -4
Math.Truncate(-3.4) = -3
尽管
Math.Floor(3.4) = 3
Math.Truncate(3.4) = 3
一些例子:
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
它们在功能上与正数等效。不同之处在于它们处理负数的方式。
例如:
Math.Floor(2.5) = 2
Math.Truncate(2.5) = 2
Math.Floor(-2.5) = -3
Math.Truncate(-2.5) = -2
附:当心 Math.Round 它可能不是你所期望的。
要获得“标准”舍入结果,请使用:
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
Math.Floor()
符合条件的“朝向负无穷大” IEEE 标准 754 第 4 节。
Math.Truncate()
将“四舍五入到最接近零的整数。”
math.floor()
返回小于或等于指定数字的最大整数。
微软软件定义网络 系统.数学.floor
math.truncate()
计算数字的整数部分。
微软软件定义网络 系统.数学.截断
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
此外 数学.Round()
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
Math.floor
向左滑动...
Math.ceil
向右滑动...
Math.truncate
criiiiss crooooss(下限/上限始终朝向 0)
Math.round
恰恰,真流畅……(走到最近的一侧)
咱们上班去!(⌐□_□)
向左转... Math.floor
你们现在就收回去吧... --
这次跳了两... -=2
大家拍手✋✋
你能降到多低?可以低点吗?一路到 floor
?
if (this == "wrong")
return "i don't wanna be right";
Math.truncate(x)
也同样是 int(x)
.
通过删除正分数或负分数,你总是会趋向于 0。
Math.Floor()
: :返回小于或等于指定双精度浮点数的最大整数。
Math.Round()
: :将值四舍五入为最接近的整数或指定的小数位数。
Mat.floor()
将始终向下舍入,即,它返回较小的整数。尽管 round()
将返回最接近的整数