Skip to content

Integer Overflow

快速摘要

你的 calculation exceeded 最大值值 数字类型能 持有, producing unexpected result.

为什么发生

  • Multiplying or exponentiating 大数字

  • Accumulating 值 in 循环不使用边界

  • Factorial or Fibonacci 的大 输入

最小示例

✗ 错误代码
console.log(2 ** 53 + 1 === 2 ** 53); // true — precision lost!
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
✓ 修复代码
console.log(BigInt(2) ** BigInt(53) + BigInt(1) === BigInt(2) ** BigInt(53)); // false
console.log(2n ** 53n + 1n); // 9007199254740993n (exact)

JavaScript 数字 lose precision above 2^53. 2^53 + 1 equals 2^53 due 到 rounding. Using BigInt preserves 精确 integer 值 regardless 的大小.

如何诊断

  • 检查如果 result 是无穷大, 负, or unexpectedly 小

  • Compare result 使用数字.MAX_SAFE_INTEGER

  • Log 中级值 到查找哪里 overflow occurs

如何修复

  • Use BigInt for arbitrarily 大 integers in JavaScript

  • Use modular arithmetic 到 keep 数字 bounded

  • 验证输入到 prevent overflow 之前它 happens

如何预防

  • Use BigInt 当工作使用 very 大数字

  • 验证输入到 keep calculations 在内 safe 范围

相关资源

相关术语

相关课程

← 返回语言