HomoCivicus

TUSUR 29.05.2019

May 29th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Класс для выполнения операций с дробями
  5. class Fraction {
  6. private:
  7.     int first, second;
  8.  
  9.     // Наибольший общий делитель (алгоритм Евклида)
  10.     int gcd(int x, int y) {
  11.         while (x != y) {
  12.             if (x > y) {
  13.                 x -= y;
  14.             }
  15.             else {
  16.                 y -= x;
  17.             }
  18.         }
  19.  
  20.         return x;
  21.     }
  22.  
  23. public:
  24.     // Ввод с клавиатуры
  25.     void read() {
  26.         do {
  27.             cout << "Числитель: ";
  28.             cin >> first;
  29.         } while (first < 1);
  30.         cout << "\n";
  31.  
  32.         do {
  33.             cout << "Знаменатель: ";
  34.             cin >> second;
  35.         } while (second < 1);
  36.         cout << "\n";
  37.     }
  38.  
  39.     // Сокращение дроби на НОД числителя и знаменателя
  40.     void reduce() {
  41.         int divisor = gcd(first, second);
  42.  
  43.         first /= divisor;
  44.         second /= divisor;
  45.     }
  46.  
  47.     // Вывод на экран
  48.     void display() {
  49.         cout << "Дробь: " << first << "/" << second;
  50.     }
  51. };
  52.  
  53. int main() {
  54.     // Пример работы с объектами класса
  55.  
  56.     Fraction frac;
  57.    
  58.     frac.read();
  59.     frac.reduce();
  60.     frac.display();
  61.  
  62.     return 0;
  63. }
Add Comment
Please, Sign In to add comment