Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fraction and Calculator
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 class FractionCalculator {
public Fraction add(Fraction first, Fraction second) { // принимает две дроби
Fraction result = new Fraction(1, 1);
if (first.denominator == second.denominator) { //если знаменатели одинаковые
result.denominator = first.denominator;
result.numerator = first.numerator + second.numerator;
} else {
int nok = nok(first.denominator, second.denominator);
result.denominator = nok;
result.numerator = first.numerator * (nok / first.denominator) + second.numerator * (nok / second.denominator);
}
return result;
}
public Fraction multiply(Fraction first, Fraction second) { // принимает две дроби
Fraction result = new Fraction(1, 1);
result.denominator = first.denominator * second.denominator;
result.numerator = first.numerator * second.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;
}
}
public class FractionTest {
public static void main(String[] args) {
FractionCalculator calculator = new FractionCalculator(); // сначала создаем калькулятор
Fraction frac1 = new Fraction(3, 4);
Fraction frac2 = new Fraction(1, 5);
Fraction sum = calculator.add(frac1, frac2);
System.out.println(frac1 + " + " + frac2 +" = " + sum);
Fraction mult = calculator.multiply(frac1, 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