Сравняване на рац. числа

mail@pastecode.io avatar
unknown
csharp
a year ago
2.3 kB
1
Indexable
Never
using System;

namespace RationalCalc
{ 
    class Rational
    { 
        int num;
        int den;
        public Rational(Rational r)
        {
            this.num = r.num;
            this.den = r.den;
        }
        public Rational(int n, int d)
        {
            this.num = n;
            this.den = d;
            normalize();
        }
        public double getDec()
        {
            return (double)this.num / this.den;
        }
        public string print()
        {
            return string.Format("{0}/{1}", this.num, this.den);
        }
        public Rational multi(Rational r)
        {
            return new Rational(this.num * r.num, this.den *= r.den);
        }
        public Rational dev(Rational r)
        {
            return new Rational(this.num * r.den, this.den * r.num);
        }
        public Rational sum(Rational r)
        {
            int a = this.num * r.den + r.num * this.den;
            int b = this.den * r.den;
            return new Rational(a, b);
        }
        public Rational sub(Rational r)
        {
            int a = this.num * r.den - r.num * this.den;
            int b = this.den * r.den;
            return new Rational(a, b);
        }
        public int compare(Rational r)
        {
            int a = this.num * r.den;
            int b = r.num * this.den;
            if (a > b)
            {
                return 1;
            }
            else if (a < b)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }

        void normalize()
        {
            int a = Math.Abs(this.num);
            int b = Math.Abs(this.den);
            while (a != b)
            {
                if (a > b)
                {
                    a -= b;
                }
                else
                {
                    b -= a;
                }
            }
            this.num /= a;
            this.den /= b;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Rational a = new Rational(3, 2);
            Rational b = new Rational(6, 4);
            Console.WriteLine(a.compare(b));
        }
    }
}