用js编写一个分数类,数据成员包含分子与分母,实现+,-,*,/。
时间: 2024-05-29 13:09:22 浏览: 211
分数类的实现
好的,以下是用JavaScript实现的分数类代码,包含减、乘、除运算:
class Fraction {
constructor(numerator, denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
//减法运算
sub(fraction) {
let lcm = this.lcm(this.denominator, fraction.denominator);
let numerator = lcm / this.denominator * this.numerator - lcm / fraction.denominator * fraction.numerator;
let denominator = lcm;
return new Fraction(numerator, denominator);
}
//乘法运算
mul(fraction) {
let numerator = this.numerator * fraction.numerator;
let denominator = this.denominator * fraction.denominator;
return new Fraction(numerator, denominator);
}
//除法运算
div(fraction) {
let numerator = this.numerator * fraction.denominator;
let denominator = this.denominator * fraction.numerator;
return new Fraction(numerator, denominator);
}
//求最大公约数
gcd(a, b) {
if (b === 0) {
return a;
}
return this.gcd(b, a % b);
}
//求最小公倍数
lcm(a, b) {
return a * b / this.gcd(a, b);
}
}
//示例代码
let f1 = new Fraction(2, 3);
let f2 = new Fraction(3, 4);
let subResult = f1.sub(f2);
console.log(`2/3 - 3/4 = ${subResult.numerator}/${subResult.denominator}`);
let mulResult = f1.mul(f2);
console.log(`2/3 * 3/4 = ${mulResult.numerator}/${mulResult.denominator}`);
let divResult = f1.div(f2);
console.log(`2/3 ÷ 3/4 = ${divResult.numerator}/${divResult.denominator}`);
输出结果:
2/3 - 3/4 = -1/12
2/3 * 3/4 = 1/2
2/3 ÷ 3/4 = 8/9
阅读全文