0

我正在尝试创建一个函数,将数字四舍五入到给定数字的最接近的倍数作为整数。

所以如果数字是 15 我们有

  • 14,4 轮到 15
  • -14,4 轮到 -15
  • 14,5 轮到 15
  • 28轮到30轮
  • -28 轮到 -30

等等。我已经编写了一些代码,但似乎没有按预期工作:

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;
}
4

1 回答 1

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!!!");
    }
于 2015-08-13T08:29:58.530 回答