簡體   English   中英

BigInteger從int到BigInteger的轉換

[英]BigInteger Conversion from int to BigInteger

我在使用BigIntegers時遇到麻煩。 我在Rational類中使用add方法遇到麻煩。 Rational(int x, int y)構造函數中,我試圖通過使用toString(int n)方法將參數數據類型int轉換為BigInteger的實例變量數據類型。

  1. 我是否在Rational(int x, int y)構造函數中正確進行了轉換?
  2. 他們寫了add方法,我在所有n.num和n.den下都遇到了錯誤。 我不明白為什么會收到該錯誤。 我不是正確使用BigInteger類的add方法嗎? http://docs.oracle.com/javase/1.4.2/docs/api/java/math/BigInteger.html

假設一個類具有以下內容

Rational a = new Rational(1,2);
Rational b = new Rational(1,3);
Rational c = new Rational(1,6);
Rational sum = a.add(b).add(c);
println(sum);

而Rational類包括

import acm.program.*;
import java.math.*;

public class Rational{

    public Rational(int x, int y) {
        num = new BigInteger(toString(x));
        den = new BigInteger(toString(y));
    }

    public toString(int n) {
        return toString(n); 
    }

    public BigInteger add(BigInteger n) {
        return new BigInteger(this.num * n.den + n.num * this.den, this.den *  n.den)
    }

    /*  private instance variables  */
    private BigInteger num; 
    private BigInteger den;
}

要將int轉換為BigInteger,我將使用BigInteger.valueOf(int)

另外,您不能將運算符與BigIntegers一起使用,必須使用其自己的方法。 您的方法應該是這樣的:

public Rational add(Rational n) {
    return new Rational(
             this.num.multiply(n.den).add(n.num.multiply(this.den)).intValue(),
             this.den.multiply(n.den).intValue());
}

一個簡單的錯誤:

public Rational add(Rational n) {
    return new Rational(
        this.num.multiply(n.den).add(n.num.multiply(this.den)),
        this.den.multiply(n.den));
}

另外,在創建新的BigInteger ,應使用valueOf(int)方法,而不是轉換為String

1)我可以在Rational(int x,int y)構造函數中正確地進行轉換嗎?

您可以使用

BigInteger num = BigInteger.valueOf(x);

不需要先創建字符串。

2. They way the add method is written I'm getting an error .....

您的添加方法是錯誤的,並且不清楚您要在添加方法中實現什么。 但是,如果要在BigInteger中進行加法,則應使用BigInteger#add方法,對於BigInteger之間的乘法,應使用BigInteger#multiply方法。

為了阻止分母呈指數增長,我將使用兩個分母中的最小公倍數作為結果的分母,而不是它們的乘積。 看起來像這樣。

public Rational add(Rational rhs) {
    BigInteger commonFactor = den.gcd(rhs.den);
    BigInteger resultNumerator = 
        num.multiply(rhs.den).add(rhs.num.multiply(den)).divide(commonFactor);
    BigInteger resultDenominator = den.multiply(rhs.den).divide(commonFactor);

    return new Rational(resultNumerator, resultDenominator);
}

要完全按照我的用法來使用它,您需要一個帶有兩個BigInteger參數的新構造函數。 但是您可能還是想要這樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM