Created
February 13, 2017 09:56
-
-
Save MasterAlish/880ab508a01c23e665f15a0a35397997 to your computer and use it in GitHub Desktop.
Fractions in single file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Fraction { //Дробь | |
public int denominator; //Знаменатель | |
public int numerator; //Числитель | |
public Fraction(int numerator, int denominator) { | |
this.denominator = denominator; | |
this.numerator = numerator; | |
} | |
public String toString() { | |
return numerator + "/" + denominator; | |
} | |
public Fraction add(Fraction other) { | |
Fraction result = new Fraction(1, 1); | |
if (this.denominator == other.denominator) { //если знаменатели одинаковые | |
result.denominator = this.denominator; | |
result.numerator = this.numerator + other.numerator; | |
} else { | |
int nok = nok(this.denominator, other.denominator); | |
result.denominator = nok; | |
result.numerator = this.numerator * (nok / this.denominator) + other.numerator * (nok / other.denominator); | |
} | |
return result; | |
} | |
public Fraction multiply(Fraction other) { | |
Fraction result = new Fraction(1, 1); | |
result.denominator = this.denominator * other.denominator; | |
result.numerator = this.numerator * other.numerator; | |
return result; | |
} | |
private int nod(int a, int b) { // Наибольший общий делитель | |
return b == 0 ? a : nod(b, a % b); | |
} | |
private int nok(int a, int b) { // Наименьшее общее кратное | |
return a / nod(a, b) * b; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FractionTest { | |
public static void main(String[] args) { | |
Fraction frac1 = new Fraction(3, 4); | |
Fraction frac2 = new Fraction(1, 5); | |
Fraction sum = frac1.add(frac2); | |
System.out.println(frac1 + " + " + frac2 +" = " + sum); | |
Fraction mult = frac1.multiply(frac2); | |
System.out.println(frac1 + " * " + frac2 +" = " + mult); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment