将两个数字四舍五入到最接近的均分数的算法

问题描述 投票:0回答:2

我知道标题的措辞不太好,但是无法想到更好的书写方式。

这里是场景-我有两个输入框,都代表整数。一个代表我们的单位,另一个代表供应商的单位。有一个乘数定义了如何从我们的转换到他们的。在下面的示例中,我说的是我们的两个单位等于五个。因此,例如,>

decimal multiplier = 0.4; // Two of our units equals five of theirs
int requestedQuantity = 11; // Our units
int suppliedQuantity = 37; // Their units

// Should return 12, since that is the next highest whole number that results in both of us having whole numbers (12 of ours = 30 of theirs)
int correctedFromRequestedQuantity = GetCorrectedRequestedQuantity(requestedQuantity, null, multiplier); 

// Should return 16, since that is the next highest whole number that results in both of us having whole numbers (16 of ours = 40 of theirs);
int correctedFromSuppliedQuantity = GetCorrectedRequestedQuantity(suppliedQuantity, multiplier, null);

这是我编写的用于处理此问题的函数。我没有在乘法器/舍入器上进行零除检查,因为我已经在其他地方进行了检查。进行所有这些转换似乎很疯狂,但是有更好的方法吗?

public int GetCorrectedRequestedQuantity(int? input, decimal? multiplier, decimal? rounder)
{
  if (multiplier == null)
  {
    if (rounder == null)
      return input.GetValueOrDefault();
    else
      return (int)Math.Ceiling((decimal)((decimal)Math.Ceiling(input.GetValueOrDefault() / rounder.Value) * rounder.Value));
  }
  else if (input.HasValue)
  {
    // This is insane...
    return (int)Math.Ceiling((decimal)((decimal)Math.Ceiling((int)Math.Ceiling((decimal)input * multiplier.Value) / multiplier.Value) * multiplier.Value));
  }
  else
    return 0;
}

我知道标题的措辞不太好-尽管无法想到更好的书写方式。这是场景-我有两个输入框,都代表整数。一个是...

c# math rounding
2个回答
2
投票

用最小的项将乘数表示为分数。我不知道.NET是否具有分数类,但是如果没有,您可能可以找到C#实现,或者只是编写自己的实现。因此,假设乘数是用最低限度的两个整数a / b


0
投票

我最好的主意是半蛮力。听起来好像基本上是Fraction Mathematics。因此,可能有一种更简便的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.