gpt4 book ai didi

java - 化简分数,Java

转载 作者:太空宇宙 更新时间:2023-11-04 12:38:13 26 4
gpt4 key购买 nike

我正在做一个学校项目,其中我添加了 2 个分数,需要简化答案。到目前为止,我已经有了很多代码,但在某些情况下,某些分数没有正确简化。例如 1/4+1/6 1ill 给出 5/6 而不是 5/12。您能否检查我的代码是否有任何可能的错误或指针?

public int num1, num2, denom1, denom2, numSum, denomAns, denomSimp, gcd;

public Fraction(int a1, int a2, int a3, int a4, int a5, int a6) {
this.num1 = a1;
this.num2 = a2;
this.denom1 = a3;
this.denom2 = a4;
this.numSum = a5;
this.denomAns = a6;
}

public void simplify() {

if (denom1 == denom2) {
denomAns = denom1;
numSum = num1 + num2;
} else {
denomAns = denom1 * denom2;
num1 = num1 * denom2;
num2 = num2 * denom1;
numSum = num1 + num2;
}
int tempNum = numSum, tempDenom = denomAns;
if (tempNum == 0) {
gcd = tempDenom;
} else {
while (tempDenom != 0) {
if (tempNum > tempDenom) {
tempNum = tempNum - tempDenom;
} else {
tempDenom = tempDenom - tempNum;
}
}
gcd = tempNum;
}
denomSimp = denomAns / gcd;
numSum = numSum / gcd;
}

最佳答案

package test;

public class Fraction {

private int num1;
private int num2;
private int denom1;
private int denom2;

private int num;
private int denom;

public Fraction(int num1, int num2, int denom1, int denom2) {
this.num1 = num1;
this.num2 = num2;
this.denom1 = denom1;
this.denom2 = denom2;
}

public void sum() { //sum the two fractions
num = (num1 * denom2) + (num2 * denom1);
denom = denom1 * denom2;
}

public void simplify() {

int gcd = gcd(num, denom);

num = num / gcd;
denom = denom / gcd;
}

public int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}

public static void main(String[] args) {
Fraction fraction = new Fraction(1,1,4,6); // 1/4 and 1/6
fraction.sum();
fraction.simplify();
System.out.println("Simplified : " + fraction.getNumSimp() + "/" + fraction.getDenomSimp());
}

public int getNumSimp() {
return num;
}

public int getDenomSimp() {
return denom;
}

}

关于java - 化简分数,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37094481/

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