用Javascript写分数运算
时间: 2024-06-06 14:11:06 浏览: 96
以下是使用JavaScript进行分数运算的示例代码:
// 定义分数对象
function Fraction(numerator, denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
// 分数加法
Fraction.prototype.add = function(other) {
var gcd = this.gcd(this.denominator, other.denominator);
var lcm = this.lcm(this.denominator, other.denominator, gcd);
var numerator = (this.numerator * lcm / this.denominator) + (other.numerator * lcm / other.denominator);
return new Fraction(numerator, lcm);
}
// 分数减法
Fraction.prototype.subtract = function(other) {
var gcd = this.gcd(this.denominator, other.denominator);
var lcm = this.lcm(this.denominator, other.denominator, gcd);
var numerator = (this.numerator * lcm / this.denominator) - (other.numerator * lcm / other.denominator);
return new Fraction(numerator, lcm);
}
// 分数乘法
Fraction.prototype.multiply = function(other) {
var numerator = this.numerator * other.numerator;
var denominator = this.denominator * other.denominator;
return new Fraction(numerator, denominator);
}
// 分数除法
Fraction.prototype.divide = function(other) {
var numerator = this.numerator * other.denominator;
var denominator = this.denominator * other.numerator;
return new Fraction(numerator, denominator);
}
// 求最大公约数
Fraction.prototype.gcd = function(a, b) {
if (b === 0) {
return a;
} else {
return this.gcd(b, a % b);
}
}
// 求最小公倍数
Fraction.prototype.lcm = function(a, b, gcd) {
return (a * b) / gcd;
}
// 测试分数运算
var frac1 = new Fraction(1, 2);
var frac2 = new Fraction(2, 3);
console.log(frac1.add(frac2)); // 输出结果为5/6
console.log(frac1.subtract(frac2)); // 输出结果为-1/6
console.log(frac1.multiply(frac2)); // 输出结果为1/3
console.log(frac1.divide(frac2)); // 输出结果为3/4
阅读全文