【问题标题】:Ecmascript bigint, round to evenEcmascript bigint,四舍五入
【发布时间】:2018-12-12 22:30:23
【问题描述】:

我正在使用 ESNext 的 bigint 功能。做除法时,bigint 舍入为 0。举个例子:

有数字:

> 3000 / 1578
1.9011406844106464

使用大整数:

3000n / 1578n
1n

我想编写一个可以进行除法但使用银行家四舍五入(四舍五入)的函数,而不是四舍五入。

例子

function divide(a, b) {
  return a/b;
}

我只是有点困惑如何编写我的divide 函数,并使用余数四舍五入。这是我尝试过的:

function divide(a, b) {
  let result = a/b;
  // if modulo is over half the divisor
  if ((a % b) * 2n > b) {
     // Add 1 if result is odd
     if (result % 2n === 1n) result++;
  } else {
     // Remove 1 if result is even
     if (result % 2n !== 1n) result--;
  }
  return result;
}

这为我提供了divide(3000n, 1578n) 的正确结果,但我注意到这将为我提供divide(7n, 2n) 的错误结果,我希望将其四舍五入为4n。

【问题讨论】:

    标签: javascript rounding bigint


    【解决方案1】:

    银行家的四舍五入只影响余数正好是除数一半的除法。所有其他情况均进行正常舍入。

    我认为你的函数应该修改如下:

    function divide(a, b) {
    
      // Make A and B positive
      const aAbs = a > 0 ? a : -a;
      const bAbs = b > 0 ? b : -b;
    
      let result = aAbs/bAbs;
      const rem = aAbs % bAbs;
      // if remainder > half divisor, should have rounded up instead of down, so add 1
      if (rem * 2n > bAbs) {
          result ++;
      } else if (rem * 2n === bAbs) {
          // Add 1 if result is odd to get an even return value
          if (result % 2n === 1n) result++;
      }
    
      if (a > 0 !== b > 0) {
        // Either a XOR b is negative, so the result has to be
        // negative as well.
        return -result;
      } else {
        return result;
      }
    }
    console.log(divide(3000n, 1578n));
    console.log(divide(7n, 2n));
    console.log(divide(-7n, 2n));

    【讨论】:

    • 这是一个很好的解决方案。越来越近,但仍然因负数而失败。我正在尝试根据您的结果弄清楚。到目前为止,我感谢您的帮助!
    • 也许您可以对绝对值进行除法,然后将否定(如果没有被 a 和 b 都为负数抵消)应用于最终结果
    • 好主意。我刚刚用这个建议更新了你的答案。这通过了我所有的测试用例,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-01-12
    • 2012-08-04
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    相关资源
    最近更新 更多