in c# convert the code below that uses Rational Methods to use Overloaded Operators. using System; /*
Question:
in c#
convert the code below that uses Rational Methods to use Overloaded Operators.
using System;
/* 10.8 (Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write an app to test your class. Use integer variables to represent the private instance variables of the classthe numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it's declared. The constructor should store the fraction in reduced form. The fraction */ namespace Exercise_10_08 { class Program { static void Main(string[] args) { Rational Fraction1 = new Rational(5, 10);//to change fraction do so here Rational Fraction2 = new Rational(5, 10); Console.WriteLine("Fraction1 = " + Fraction1); Console.WriteLine("Fraction2 = " + Fraction2); Console.WriteLine("Fraction1 + Fraction2 = " + (Fraction1 + Fraction2)); Console.WriteLine("Fraction1 - Fraction2 = " + (Fraction1 - Fraction2)); Console.WriteLine("Fraction1 * Fraction2 = " + (Fraction1 * Fraction2)); Console.WriteLine("Fraction1 / Fraction2 = " + (Fraction1 / Fraction2)); }
class Rational { private int top; private int bot; public Rational(int numerator, int denominator) { this.top = numerator; this.bot = denominator; Reduce(); } private void Reduce() { int gcd = Gcd(top, bot); top /= gcd; bot /= gcd; } private int Gcd(int a, int b) { if (b == 0) { return a; } else { return Gcd(b, a % b); } } public static Rational operator +(Rational Fraction1, Rational Fraction2) { int numerator = Fraction1.top * Fraction2.bot + Fraction1.bot * Fraction2.top; int denominator = Fraction1.bot * Fraction2.bot; return new Rational(numerator, denominator); } public static Rational operator -(Rational Fraction1, Rational Fraction2) { int numerator = Fraction1.top * Fraction2.bot - Fraction1.bot * Fraction2.top; int denominator = Fraction1.bot * Fraction2.bot; return new Rational(numerator, denominator); } public static Rational operator *(Rational Fraction1, Rational Fraction2) { int numerator = Fraction1.top * Fraction2.top; int denominator = Fraction1.bot * Fraction2.bot; return new Rational(numerator, denominator); } public static Rational operator /(Rational Fraction1, Rational Fraction2) { int numerator = Fraction1.top * Fraction2.bot; int denominator = Fraction1.bot * Fraction2.top; return new Rational(numerator, denominator); } public override string ToString() { if (bot == 1) { return top.ToString(); } else { return top + "/" + bot; } } } } }
Java How To Program Late Objects Version
ISBN: 9780136123712
8th Edition
Authors: Paul Deitel, Deitel & Associates