gpt4 book ai didi

Java ADT调用变量

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

我是 Java 新手,我正在尝试创建一个 ADT。我的 ADT 涉及通过输入分子和分母来创建和处理分数。我希望我的方法之一将两个分数相加,并根据两个和的 gcd 返回一个简化分数。我遇到的问题是实例化两个分数的组成部分(分子和分母)。该方法应该采用一个分数 other,表示为 public Rational add(Rational other)。我分配的第一个变量是

int d1 = this.denominator;
int d2 = other.denominator;

但这似乎不起作用。以下是迄今为止的方法:

public Rational add(Rational other){
int d1 = this.denominator;
int d2 = other.denominator;
int dtotal = d1*d2;
int n1 = this.numerator*d2;
int n2 = other.numerator*d1;
int ntotal = n1+n2;
if(ntotal>dtotal){
for(int i=1; i<=ntotal; i++){
if(ntotal%i==0 && dtotal%i==0){
gcd=i;
}
}
}else if(dtotal>ntotal){
for(int i=1;i<=dtotal;i++){
if(dtotal%i==0 && ntotal%i==0){
gcd=i;
}
}
}else if(dtotal==ntotal){
gcd=numerator;
}
numerator = ntotal/gcd;
denominator = dtotal/gcd;
}

最佳答案

您需要使用所需的方法在类外部定义接口(interface)。这是示例,请根据您的需要进行编辑。

interface Rational {    
public int getNumerator();
public int getDenominator();
public Rational add(Rational other);
public Rational multiply(Rational other);
public int compareTo(Rational other);
}

现在你的类应该这样定义:

public class RationalC implements Rational {

int gcd;
int numerator;
int denominator;


@Override
public int getNumerator() {
return numerator;
}

@Override
public int getDenominator() {
return denominator;
}

@Override
public Rational add(Rational other) {
return null;
}

@Override
public Rational multiply(Rational other) {
return null;
}

@Override
public int compareTo(Rational other) {
return 0;
}
}

添加您的 addmultiply 方法定义。使用 getNumerator()getDenominator() 访问值,而不是直接访问它们。

关于Java ADT调用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32676575/

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