我正在尝试创建一个函数,将一个数字舍入到给定数字的最接近的倍数作为整数。
所以,如果数字是15,我们有
等等。我已经有了一些代码,但似乎没有按预期工作:
public static int RoundToFactor(float number, float Factor)
{
int returnNumber;
if((number%Factor) == 0) {
returnNumber = (int)number;
}
returnNumber = (int) (Mathf.Round(number/Factor)*Factor);
return returnNumber;
}
答案 0 :(得分:0)
这是我制作的方法。它应该适合您的需求。我添加了一个额外的参数,要求在它同样接近时向上或向下舍入。 (如果你注意到这些数字看起来像是错误的,例如199舍入到最接近因子2舍入,如果必要,则为200.将199改为-199,结果变为-198,这不是它只是一个小问题。)
public static double RoundToFactor(double Number, int Factor, bool RoundDirection = true)
{/*round direction: in the event that the distance is
* equal from both next factors round up (true) down (false)*/
double multiplyBy;
if ((Number % Factor).Equals(0f))
{
return Number;
}
else
{
multiplyBy = Math.Round(Number / Factor);
int Low = (int)multiplyBy - 1;
int Mid = (int)multiplyBy;
int High = (int)multiplyBy + 1;
List<double> li = new List<double>() { Low, Mid, High };
double minDelta = double.MaxValue;
double Closest = 0d;
foreach (double dbl in li)
{
double db = dbl * Factor;
double Delta = (db < Number) ? (Number - db) : (db - Number);
if (RoundDirection ? Delta <= minDelta : Delta < minDelta)
{
minDelta = Delta;
Closest = db;
}
}
return Closest;
}
throw new Exception("Math has broken!!!");
}