Hallo, ich habe den folgende Code, um arithmetische Operation durchzuführen. Die Berechnungen sind falsch außer addition:
Ich habe eine Stunde gekämpft, aber ich bin nicht weitergekommen. Vielleicht kann jemand mir eine Hilfsstellung geben? Hier ist den Code
Java:
9/7
1/5
addition:
52/35 //passt
subtraction:
8855/6125 //sollte 38/35 sein
multiply:
61985/1071875 //sollte 9/35 sein
divide:
1549625/42875 //sollte 45/7 sein
Ich habe eine Stunde gekämpft, aber ich bin nicht weitergekommen. Vielleicht kann jemand mir eine Hilfsstellung geben? Hier ist den Code
Java:
package F;
public class FractionTypVorlesung {
int numer;
int denom;
public FractionTypVorlesung(int n, int d){
numer = n;
denom = d;
//reduce();
}
public void reduce(int numer, int denom){
int GCD = gcd(numer, denom);
numer /= GCD;
denom /= GCD;
}
public void add (FractionTypVorlesung other){
numer *= other.denom;
other.numer *= denom;
denom *= other.denom;
other.denom *= denom;
numer+= other.numer;
reduce(numer, denom);
System.out.println(numer + "/" + denom);
}
public void sub(FractionTypVorlesung other) {
int newNumer = this.numer * other.denom - other.numer * this.denom;
int newDenom = this.denom * other.denom;
reduce(newNumer, newDenom);
System.out.println(newNumer + "/" + newDenom);
}
public void multiply(FractionTypVorlesung other) {
int newNumer = this.numer * other.numer;
int newDenom = this.denom * other.denom;
reduce(newNumer, newDenom);
System.out.println(newNumer + "/" + newDenom);
}
public void div(FractionTypVorlesung other) {
int newNumer = this.numer * other.denom;
int newDenom = this.denom * other.numer;
reduce(newNumer, newDenom);
System.out.println(newNumer + "/" + newDenom);
}
public int gcd(int a, int b){
if(b==0){
return a;
}
return gcd(b, a%b);
}
public String toString(){
return Integer.toString(numer) + "/" + Integer.toString(denom);
}
public static void main(String[] args) {
FractionTypVorlesung a = new FractionTypVorlesung(9,7);
FractionTypVorlesung b = new FractionTypVorlesung(1, 5);
System.out.println(a.toString());
System.out.println(b.toString());
System.out.println("addition: ");
a.add(b);
System.out.println("subtraction: ");
a.sub(b);
System.out.println("multiply: ");
a.multiply(b);
System.out.println("divide: ");
a.div(b);
}
}