gpt4 book ai didi

java - 我的 Rational 代码的主要方法

转载 作者:太空宇宙 更新时间:2023-11-04 11:50:15 25 4
gpt4 key购买 nike

所以我已经完成了有理数测试的代码,包括有理数的加法、减法等。我一直试图创建实际输出代码的主类。

这是我的 Rational 类的代码:

package rational;

public class Rational {

private static int gcd(int u, int v) {
if (u == 0) {
return v;
} else if (v == 0) {
return u;
} else if (u == 1 || v == 1) {
return 1;
}
int temp;
while (v != 0) {
temp = u % v;
u = v;
v = temp;
}
return u;
}

private static Rational reduce(Rational num) {
int gcd = gcd(num.getNumerator(), num.getDenominator());
return new Rational(num.getNumerator() / gcd, num.getDenominator() / gcd);
}

private static Rational neg(Rational num) {
return new Rational(-(num.getNumerator()), num.getDenominator());
}

public static Rational add(Rational a, Rational b) {
return reduce(new Rational(a.getNumerator() * b.getDenominator() + a.getDenominator() * b.getNumerator(), a.getDenominator() * b.getDenominator()));
}

public static Rational subtract(Rational a, Rational b) {
return add(a, neg(b));
}

public static Rational multiply(Rational a, Rational b) {
return reduce(new Rational(a.getNumerator() * b.getNumerator(), a.getDenominator() * b.getDenominator()));
}

public static Rational divide(Rational a, Rational b) {
return multiply(a, new Rational(b.getDenominator(), b.getNumerator()));
}

public static String getString(Rational num) {
return String.format("%d/%d", num.getNumerator(), num.getDenominator());
}

public static String getFloatString(Rational num) {
return getFloatString(num, 6);
}

public static String getFloatString(Rational num, int fixedTo) {
return String.format("%." + fixedTo + "f", num.getNumerator() / ((float) num.getDenominator()));
}

private final int numerator;
private final int denominator;

public Rational() {
this(0, 1); // Note that division by zero is not allowed
}

public Rational(int numerator, int denominator) {
if (denominator == 0) {
throw new ArithmeticException("Division by zero");
}
this.numerator = numerator;
this.denominator = denominator;
}

public int getNumerator() {
return numerator;
}

public int getDenominator() {
return denominator;
}

}

最佳答案

首先,如果您想在 Rational 类中创建一个 main 方法,并调用您的方法:

您可以创建一个像这样的 main 方法:

public static void main(String[] args) {
//Create a Rational with an empty constructor
Rational r1 = new Rational();
int numerator = 1, denominator = 2;
//Create a Rational with an the second constructor that take two int
Rational r2 = new Rational(numerator, denominator);
//then you can use your methods like this.
r2.gcd(numerator, numerator);
}

就像您可以调用采用具有相同对象 r2 的 Rational 对象的方法一样:

r1.reduce(r2);

r2.reduce(r2);

注意

如果您想在另一个类中创建 main 方法,请确保将您的方法更改为 puclic

希望这可以帮助你。

关于java - 我的 Rational 代码的主要方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41907487/

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