面试题答案
一键面试- 核心代码思路:
- 利用
BigInt
或第三方高精度计算库(如decimal.js
)来处理浮点数运算,避免JavaScript原生浮点数精度问题。 - 将浮点数转换为整数进行运算,运算完成后再转换回浮点数。
- 利用
- 关键步骤:
- 使用
decimal.js
库:- 引入
decimal.js
库。
const Decimal = require('decimal.js');
- 定义计算函数,例如计算投资组合收益(假设投资金额数组
amounts
,收益率数组rates
):
function calculatePortfolioReturn(amounts, rates) { let totalReturn = new Decimal(0); for (let i = 0; i < amounts.length; i++) { let investment = new Decimal(amounts[i]); let rate = new Decimal(rates[i]); let returnValue = investment.mul(rate); totalReturn = totalReturn.add(returnValue); } return totalReturn.toNumber(); }
- 引入
- 利用
BigInt
:- 确定浮点数的小数位数,以便转换为整数。
- 将浮点数转换为
BigInt
进行运算。例如,对于加法运算:
function addNumbers(a, b) { const decimalPlaces = Math.max( (a.toString().split('.')[1] || '').length, (b.toString().split('.')[1] || '').length ); const multiplier = BigInt(10 ** decimalPlaces); const aInt = BigInt(a * multiplier); const bInt = BigInt(b * multiplier); const resultInt = aInt + bInt; return Number(resultInt) / multiplier; }
- 对于其他运算(减、乘、除)类似,先转换为
BigInt
进行运算,再转换回浮点数。例如乘法:
function multiplyNumbers(a, b) { const decimalPlaces = Math.max( (a.toString().split('.')[1] || '').length, (b.toString().split('.')[1] || '').length ); const multiplier = BigInt(10 ** decimalPlaces); const aInt = BigInt(a * multiplier); const bInt = BigInt(b * multiplier); const resultInt = aInt * bInt; return Number(resultInt) / (multiplier * multiplier); }
- 使用