Javascript理性-保留1的分母
我需要在Javascript中使用分母为1的有理数。所以,我有一些输入值,比如1024,我需要将其存储为1024/1。当然,Javascript理性-保留1的分母,javascript,rational-numbers,Javascript,Rational Numbers,我需要在Javascript中使用分母为1的有理数。所以,我有一些输入值,比如1024,我需要将其存储为1024/1。当然,1024/1只给我1024。那么我如何才能获得原始的理性版本呢?你打算如何处理理性?如果只是简单的算术,你可以自己写 下面是一个示例,您可以为其他操作符执行类似的操作 希望这有帮助 function Rational(n, d) { this.n = n; this.d = d; } Rational.prototype.multiply = functio
1024/1
只给我1024。那么我如何才能获得原始的理性版本呢?你打算如何处理理性?如果只是简单的算术,你可以自己写
下面是一个示例,您可以为其他操作符执行类似的操作
希望这有帮助
function Rational(n, d) {
this.n = n;
this.d = d;
}
Rational.prototype.multiply = function(other) {
return this.reduce(this.n * other.n, this.d * other.d)
}
Rational.prototype.reduce = function(n, d) {
//http://stackoverflow.com/questions/4652468/is-there-a-javascript-function-that-reduces-a-fraction
var gcd = function gcd(a,b){
return b ? gcd(b, a%b) : a;
};
gcd = gcd(n,d);
return new Rational(n/gcd, d/gcd);
}
var r1 = new Rational(1, 2);
var r2 = new Rational(24, 1);
var result = r1.multiply(r2);
console.log(result); // Rational(12, 1);
console.log(result.n + '/' + result.d); // 12/1
我认为这个软件包可能会有帮助: