js实现计算
实现基本数学运算
在JavaScript中可以直接使用算术运算符进行基本计算。加法使用+,减法使用-,乘法使用*,除法使用/,取模使用%,指数运算使用。
let sum = 10 + 5; // 15
let difference = 10 - 5; // 5
let product = 10 * 5; // 50
let quotient = 10 / 5; // 2
let remainder = 10 % 3; // 1
let power = 2 3; // 8
处理浮点数精度问题
JavaScript中的浮点数计算可能会产生精度问题。使用toFixed()方法可以限制小数位数,但会返回字符串。需要转换为数字类型。
let result = 0.1 + 0.2; // 0.30000000000000004
let fixedResult = parseFloat((0.1 + 0.2).toFixed(1)); // 0.3
使用Math对象进行高级计算
JavaScript内置的Math对象提供了多种数学函数和常量。
Math.PI; // 圆周率
Math.sqrt(16); // 4,平方根
Math.pow(2, 3); // 8,幂运算
Math.abs(-5); // 5,绝对值
Math.round(4.6); // 5,四舍五入
Math.ceil(4.2); // 5,向上取整
Math.floor(4.9); // 4,向下取整
Math.max(1, 3, 2); // 3,最大值
Math.min(1, 3, 2); // 1,最小值
Math.random(); // 0到1之间的随机数
实现科学计算和三角函数
Math对象还提供了三角函数和对数函数等科学计算功能。
Math.sin(Math.PI/2); // 1,正弦函数
Math.cos(Math.PI); // -1,余弦函数
Math.tan(Math.PI/4); // 0.999...,正切函数
Math.log(Math.E); // 1,自然对数
Math.log10(100); // 2,以10为底的对数
Math.exp(1); // 2.718...,e的幂
创建计算器函数
可以封装计算功能为可重用的函数,处理更复杂的计算需求。
function calculate(operation, a, b) {
switch(operation) {
case 'add': return a + b;
case 'subtract': return a - b;
case 'multiply': return a * b;
case 'divide': return a / b;
default: throw new Error('Unknown operation');
}
}
let result = calculate('add', 5, 3); // 8
处理大数计算
对于超出JavaScript安全整数范围(±2^53-1)的大数计算,可以使用BigInt类型。
let bigNum = BigInt(9007199254740991);
let bigResult = bigNum + BigInt(1); // 9007199254740992n






