0

分母が 1 の Javascript の有理数を使用する必要があります。したがって、1024 などの入力値があり、それを 1024/1 として保存する必要があります。もちろん1024 / 1、私は 1024 を返します。では、生の有理数バージョンを取得するにはどうすればよいでしょうか?

4

1 に答える 1

0

理性で何をしようとしていますか?単純な算術演算のみの場合は、自分で書くことができます。

以下は例です。他の演算子についても同様のことを行います。

お役に立てれば

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
于 2015-11-20T21:01:15.563 に答える