- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要使用不同于默认“四舍五入”Mathf.Round()
的中点舍入规则。 Mathf.Round()
没有中点舍入参数,所以我使用 System.Math.Round()
。
C# 有不同的中点舍入策略,在此处指定:https://learn.microsoft.com/en-us/dotnet/api/system.midpointrounding?view=net-6.0 . MidpointRounding.AwayFromZero
和(显然)MidpointRounding.ToEven
在 Unity 中工作,但由于某些原因,其他的 MidpointRounding.ToZero
不工作(“CS0117:‘MidpointRounding’不包含‘ToZero’的定义”)。
float firstN = ...
float lastN = ...
int begin = (int)Math.Round(firstN, MidpointRounding.AwayFromZero); //works
int end = (int)Math.Round(lastN, MidpointRounding.ToZero); //doesn't work
我绝对需要使用 MidpointRounding.ToZero
,确实没有其他选择。我将不得不再次重写大部分代码。编写我自己的舍入函数只是为了解决这个问题听起来也不好玩。
最佳答案
MidpointRounding.ToZero
,尽管被添加到 MidpointRounding
枚举中,但也不会执行您希望它执行的操作。它只是截断数字的小数部分,为您提供离零不远的最接近的整数:
2.4 ==> 2
2.5 ==> 2
2.6 ==> 2
-2.4 ==> -2
-2.5 ==> -2
-2.6 ==> -2
很遗憾,看起来您需要自定义舍入方法,但这并不困难:
int i = (d < 0) ? (int)Math.Floor(d+0.5) : (int)Math.Ceiling(d-0.5);
结果:
2.4 ==> 2
2.5 ==> 2
2.6 ==> 3
-2.4 ==> -2
-2.5 ==> -2
-2.6 ==> -3
关于c# - MidpointRounding.ToZero 在 Unity 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71117861/
我需要使用不同于默认“四舍五入”Mathf.Round() 的中点舍入规则。 Mathf.Round() 没有中点舍入参数,所以我使用 System.Math.Round()。 C# 有不同的中点舍入
我需要使用不同于默认“四舍五入”Mathf.Round() 的中点舍入规则。 Mathf.Round() 没有中点舍入参数,所以我使用 System.Math.Round()。 C# 有不同的中点舍入
我是一名优秀的程序员,十分优秀!