gpt4 book ai didi

java - 对象的算术运算任务

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

我检查了许多有关对象操作的 stackOverflow 问题,但没有找到解决方案。

我的任务是使用这些构造函数来乘除两个对象:

public class Fraction {
private int denom;
private int counter;

public Fraction() {
this.counter = 0;
this.denom = 1;
}

public Fraction(int counter) {
this.counter = counter;
this.denom = 1;
}

public Fraction(int counter, int denom) {
this.counter = counter;
if (denom == 0) {
this.denom = 1;
} else
this.denom = denom;
}
}

“乘”和“除”方法中包含什么?

public Fraction multiply(Fraction other) {

}

public Fraction divide(Fraction other) {

}

如果这是我需要使用的:

Fraction frac1 = new Fraction (2);
Fraction frac2 = new TortSzam(3,4);
fracResult = frac1.divide(frac2);

结果是:2.6666666666666665

我在其他 StackOverflow 问题中尝试过的内容:

public Fraction multiply(Fraction other) {
final Fraction multi = this;
BigInteger result = new BigInteger;
result.multiply(other);
}

但没有成功。

提前致谢。

最佳答案

两个分数相乘只是意味着将分子相乘,然后将该乘积除以分母的乘积。所以你可以尝试:

public Fraction multiply(Fraction other) {
int counter = other.getCounter() * this.counter;
int denim = other.getDenominator() * this.denom;

return new Fraction(counter, denom);
}

我将把划分的实现留给你。作为提示,代码与上面的代码非常相似,只是您将使用两个分数输入之一(但不是全部)的倒数。

关于java - 对象的算术运算任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54090130/

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