Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created November 1, 2024 16:11
Show Gist options
  • Save sunmeat/f1f146d91e27335eba6228bff2609285 to your computer and use it in GitHub Desktop.
Save sunmeat/f1f146d91e27335eba6228bff2609285 to your computer and use it in GitHub Desktop.
fraction start example
#include <iostream>
using namespace std;
class Fraction {
int numerator;
int denominator;
// наибольший общий делитель
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
void reduce() {
int divisor = gcd(numerator, denominator);
numerator /= divisor;
denominator /= divisor;
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
}
public:
explicit Fraction() : Fraction(0, 1) {}
explicit Fraction(double decimal) : Fraction() {
denominator = 1;
while (decimal != (int)decimal) {
decimal *= 10;
denominator *= 10;
}
numerator = (int)decimal;
reduce();
}
explicit Fraction(int num, int den) {
setNumerator(num);
setDenominator(den);
}
void setNumerator(int num) {
numerator = num;
}
void setDenominator(int den) {
if (den == 0) {
throw "Знаменатель не может быть нулём.";
}
denominator = den;
}
int getNumerator() const { return numerator; }
int getDenominator() const { return denominator; }
void display() const {
cout << numerator << "/" << denominator << "\n";
}
double toDouble() const {
return (double)(numerator) / denominator;
}
Fraction add(const Fraction& other) const {
return Fraction(numerator * other.denominator + other.numerator * denominator,
denominator * other.denominator);
}
Fraction subtract(const Fraction& other) const {
return Fraction(numerator * other.denominator - other.numerator * denominator,
denominator * other.denominator);
}
Fraction multiply(const Fraction& other) const {
return Fraction(numerator * other.numerator, denominator * other.denominator);
}
Fraction divide(const Fraction& other) const {
if (other.numerator == 0) {
throw invalid_argument("Делить на ноль нельзя.");
}
return Fraction(numerator * other.denominator, denominator * other.numerator);
}
bool equals(const Fraction& other) const {
return numerator == other.numerator && denominator == other.denominator;
}
bool notEquals(const Fraction& other) const {
return !equals(other);
}
};
int main() {
setlocale(0, "");
Fraction frac1(3, 4);
Fraction frac2(2, 5);
frac1.display();
frac2.display();
Fraction sum = frac1.add(frac2);
cout << "Сумма: ";
sum.display();
Fraction difference = frac1.subtract(frac2);
cout << "Разность: ";
difference.display();
Fraction product = frac1.multiply(frac2);
cout << "Произведение: ";
product.display();
Fraction quotient = frac1.divide(frac2);
cout << "Частное: ";
quotient.display();
cout << "Десятичное значение " << frac1.getNumerator() << "/" << frac1.getDenominator() << " = " << frac1.toDouble() << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment