我在使用BigIntegers时遇到了麻烦。Rational类中的add方法有问题。在Rational(int x, int y)构造函数中,我试图通过使用toString(int n)方法将参数数据类型int转换为BigInteger的实例变量数据类型。
Rational(int x, int y)构造函数中正确地进行了转换?add方法的方式--我在n.num和n.den中得到了一个错误。我不明白为什么我会犯这个错误。我是否没有正确地使用来自BigInteger类的BigInteger方法?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;
}发布于 2013-08-28 02:10:00
要将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());
}发布于 2013-08-28 02:06:24
1)在Rational(int,int )构造函数中,我是否正确地进行了转换?
您可以使用
BigInteger num = BigInteger.valueOf(x);首先创建字符串不是必需的。
2. They way the add method is written I'm getting an error .....您的add方法是错误的,并且它不清楚您试图在add方法中实现什么。但是,如果您想在BigInteger中进行加法,您应该使用BigInteger#add方法,对于BigInteger之间的乘法,您应该使用BigInteger#multiply方法。
发布于 2013-08-28 02:06:17
一个简单的错误:
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
https://stackoverflow.com/questions/18478280
复制相似问题