170 lines
2.4 KiB
Java
170 lines
2.4 KiB
Java
public class Rational{
|
|
|
|
|
|
//Instanzvariablen
|
|
|
|
|
|
private int num;
|
|
private int denom;
|
|
private int newnum;
|
|
private int newdenom;
|
|
private int i, j; // Schleife
|
|
private double erg;
|
|
|
|
|
|
//Konstruktoren
|
|
public Rational(int n, int d){
|
|
this.num = n;
|
|
this.denom = d;
|
|
}
|
|
|
|
|
|
public Rational(int n){
|
|
this.num = n;
|
|
this.denom = 1;
|
|
}
|
|
|
|
|
|
//Methoden
|
|
|
|
public String reciprocal(){
|
|
|
|
return denom + "/" + num;
|
|
}
|
|
|
|
public String ausgabe(){
|
|
|
|
erg = (double)num/(double)denom;
|
|
|
|
return num + "/" + denom + " = " +erg;
|
|
|
|
}
|
|
|
|
|
|
//Zähler setzen
|
|
void setNum(int num)
|
|
{
|
|
this.num = num;
|
|
}
|
|
|
|
|
|
// Nenner setzen
|
|
void setDenom(int denom){
|
|
this.denom = denom;
|
|
}
|
|
|
|
//Zählerausgabe
|
|
public int getNum(){
|
|
return num;
|
|
}
|
|
|
|
|
|
//Nennerausgabe
|
|
public int getDenom(){
|
|
return denom;
|
|
}
|
|
|
|
|
|
//Kürzen
|
|
public Rational cut(){
|
|
newnum = this.num;
|
|
newdenom = this.denom;
|
|
|
|
if (this.denom < this.num){
|
|
for (i = this.denom; i > 1; i--){
|
|
if(this.denom % i == 0 && this.num % i == 0 ){
|
|
newdenom = this.denom / i;
|
|
newnum = this.num / i;
|
|
i = 2;
|
|
}
|
|
}
|
|
}
|
|
else if (this.denom > this.num){
|
|
for (i = this.num; i > 1; i--){
|
|
if(this.denom % i == 0 && this.num % i == 0 ){
|
|
newdenom = this.denom / i;
|
|
newnum = this.num / i;
|
|
i = 2;
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
return new Rational (newnum, newdenom);
|
|
}
|
|
|
|
|
|
//Addition
|
|
public Rational add(Rational onner){
|
|
|
|
if (this.denom == onner.denom){
|
|
newnum = this.num+onner.num;
|
|
newdenom = this.denom;
|
|
}
|
|
else{
|
|
|
|
newnum = this.num * onner.denom + onner.num * this.denom;
|
|
|
|
newdenom = this.denom * onner.denom;
|
|
}
|
|
|
|
Rational Wat = new Rational (newnum, newdenom);
|
|
|
|
return Wat.cut();
|
|
|
|
}
|
|
|
|
//Subtraktion
|
|
public Rational sub(Rational onner){
|
|
|
|
if (this.denom == onner.denom){
|
|
newnum = this.num-onner.num;
|
|
newdenom = this.denom;
|
|
}
|
|
else{
|
|
|
|
newnum = this.num * onner.denom - onner.num * this.denom;
|
|
|
|
newdenom = this.denom * onner.denom;
|
|
}
|
|
|
|
Rational Wat = new Rational (newnum, newdenom);
|
|
|
|
return Wat.cut();
|
|
|
|
}
|
|
|
|
|
|
//Multiplikation zweier Klassen
|
|
public Rational mult(Rational onner){
|
|
newnum = this.num * onner.getNum();
|
|
newdenom = this.denom * onner.getDenom();
|
|
|
|
Rational Wat = new Rational (newnum, newdenom);
|
|
|
|
return Wat.cut();
|
|
|
|
}
|
|
|
|
//Division zweier Brüche
|
|
public Rational div(Rational onner){
|
|
|
|
newnum = this.num * onner.denom;
|
|
newdenom = this.denom * onner.num;
|
|
|
|
Rational Wat = new Rational (newnum, newdenom);
|
|
|
|
return Wat.cut();
|
|
|
|
}
|
|
|
|
|
|
@Override
|
|
public String toString(){
|
|
return num + "/" + denom;
|
|
}
|
|
|
|
}
|
|
|
|
|