gpt4 book ai didi

java - 如何用变量初始化 Java 对象?

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

我正在尝试启动一个存储分子 p、分母 q 及其比率 r 的对象“有理数”。此代码产生不正确的答案。

class Rational { 
int p, q;
double ratio;

public Rational(){
this.p = 0;
this.q = 1;
this.ratio = this.p/(double)(this.q);
}

public static void main (String[]arg) {
Rational r1 = new Rational();

r1.p = 1;
r1.q = 7;
// r1.ratio = r1.p/(double)(r1.q); //"this line"
System.out.println (r1.p + "/" + r1.q + " = " + r1.ratio) ;
}
}

取消注释“这一行”解决了这个问题。如何定义对象,以便每次 this.pthis.q 更改时自动更新 this.r

最佳答案

在我看来,更简单的方法是定义一个名为 ratio 的函数,而不是变量。

class Rational { 
private int p, q;


public Rational(){
this.p = 0;
this.q = 1;
}

public double ratio(){
return (double)p/(double)q;
}

//define the getters and setters for p and q
}

然后,无论何时您需要该比率,您都应该调用该方法:myRational.ratio()

关于java - 如何用变量初始化 Java 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36365729/

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