js实现分数

实现分数表示和运算
在JavaScript中实现分数(Fraction)需要创建表示分数的数据结构,并实现相关运算方法(加减乘除、约分等)。以下是完整实现方案:

创建分数类
class Fraction {
constructor(numerator, denominator = 1) {
if (denominator === 0) throw new Error('Denominator cannot be zero');
this.numerator = numerator;
this.denominator = denominator;
this.normalize();
}
}
约分方法
normalize() {
const gcd = this.findGCD(Math.abs(this.numerator), Math.abs(this.denominator));
this.numerator /= gcd;
this.denominator /= gcd;
// 确保分母始终为正
if (this.denominator < 0) {
this.numerator *= -1;
this.denominator *= -1;
}
return this;
}
findGCD(a, b) {
return b === 0 ? a : this.findGCD(b, a % b);
}
加法运算
add(other) {
const newNumerator = this.numerator * other.denominator + other.numerator * this.denominator;
const newDenominator = this.denominator * other.denominator;
return new Fraction(newNumerator, newDenominator);
}
减法运算
subtract(other) {
const newNumerator = this.numerator * other.denominator - other.numerator * this.denominator;
const newDenominator = this.denominator * other.denominator;
return new Fraction(newNumerator, newDenominator);
}
乘法运算
multiply(other) {
return new Fraction(
this.numerator * other.numerator,
this.denominator * other.denominator
);
}
除法运算
divide(other) {
if (other.numerator === 0) throw new Error('Cannot divide by zero');
return new Fraction(
this.numerator * other.denominator,
this.denominator * other.numerator
);
}
转换为字符串
toString() {
if (this.denominator === 1) return `${this.numerator}`;
return `${this.numerator}/${this.denominator}`;
}
转换为小数
toDecimal() {
return this.numerator / this.denominator;
}
使用示例
const a = new Fraction(1, 2);
const b = new Fraction(3, 4);
console.log(a.add(b).toString()); // 输出 "5/4"
console.log(a.subtract(b).toString()); // 输出 "-1/4"
console.log(a.multiply(b).toString()); // 输出 "3/8"
console.log(a.divide(b).toString()); // 输出 "2/3"
console.log(a.toDecimal()); // 输出 0.5
扩展功能
对于更完整的实现,可以添加以下方法:
- 比较方法(equals, compareTo)
- 绝对值方法(abs)
- 倒数方法(reciprocal)
- 幂运算方法(pow)
这种实现方式保持了分数的精确计算,避免了浮点数运算带来的精度问题,适合需要精确分数运算的场景(如数学计算、金融应用等)。






