gpt4 book ai didi

java - 实现与有理类类似的接口(interface)(java)

转载 作者:行者123 更新时间:2023-11-30 02:39:01 25 4
gpt4 key购买 nike

我是Java初学者,这是我第一次使用Comparable接口(interface)。我不明白为什么在比较 r1 和 r2 时它总是返回零。有人可以向我解释我的代码有什么问题吗?谢谢。

public class Rational implements Comparable<Rational>{
private int num; //numerator
private int denom; //denominator

public Rational() {
num = 0;
denom = 1;
}

public Rational(int num, int denom) {
if(denom <=0 ){
throw new ArithmeticException("You cannot divide by a non-positive number");
}

this.num = num;
this.denom = denom;
}

//returns numerator of this rational number
public int getNum() {
return num;
}

//returns denominator of this rational number
public int getDenom() {
return denom;
}

public Rational add(Rational rhs) {
return new Rational(num*rhs.denom+rhs.num*denom, denom*rhs.denom);
}

public Rational subtract(Rational rhs) {
return new Rational(num*rhs.denom-rhs.num*denom, denom*rhs.denom);
}

public Rational multiply(Rational rhs) {
return new Rational(num*rhs.num, denom*rhs.denom);
}

public Rational divide(Rational rhs) {
return new Rational(num*rhs.denom, denom*rhs.num);
}

public String toString() {
String result;
if (num == 0)
result = "0";
else if(denom == 1)
result = num + "";
else
result = num + "/" + denom;
return result;
}

public int compareTo(Rational rhs){
double r1 = ((double) getNum()/getDenom());
double r2 = ((double)rhs.getNum() / rhs.getDenom());
return (int) (r1 - r2);
}

public static void main(String[] args) {
Rational r1 = new Rational(1, 2); // 1/2
Rational r2 = new Rational(3, 4); // 3/4
Rational result = r1.add(r2);
Rational result1 = r1.subtract(r2);
Rational result2 = r1.multiply(r2);
Rational result3 = r1.divide(r2);
System.out.println( "r1 + r2 = " + result + "\n" + "r1 - r2 = " + result1 + "\n" + "r1*r2 = "+ result2 + "\n" + "r1/r2 = " + result3 + "\n" + (r1.compareTo(r2)));
}
}

最佳答案

这个公式

return (int) (r1 - r2);

r1r2 之间的差异小于 1(您正在测试的情况)时,生成零。

由于通过类的构造,两个分母都是正数,因此您可以完全不使用除法进行交叉乘法和减法:

long a = (long)getNum() * rhs.getDenom();
long b = (long)rhs.getNum() * getDenom();
return Long.compare(a, b);

使用long以避免乘法溢出。

关于java - 实现与有理类类似的接口(interface)(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42314020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com