Question

In: Computer Science

Must be coded in C#. 10.8 (Rational Numbers) Create a class called Rational for performing arithmetic...

Must be coded in C#.

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 class—the 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 2/4 is equivalent to 1/2 and would be stored in the object as 1 in the numerator and 2 in the denominator. Provide a parameterless constructor with default values in case no initializers are provided. Provide public methods that perform each of the following operations (all calculation results should be stored in a reduced form): a) Add two Rational numbers. b) Subtract two Rational numbers. c) Multiply two Rational numbers. d) Divide two Rational numbers. e) Display Rational numbers in the form a/b, where a is the numerator and b is the denominator. f) Display Rational numbers in floating-point format. (Consider providing formatting capabilities that enable the user of the class to specify the number of digits of precision to the right of the decimal point.) Your program should implement exception handling if needed.

Solutions

Expert Solution

Hi. I have answered similar questions before. Here is the completed code for this problem including the code for testing. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

using System;


public class Rational {
    private int numerator;
    private int denominator;

    public Rational(int numerator, int denominator) {
        if (denominator == 0) {
            /**
             * if denominator is 0, throwing an exception.
             */
            throw new InvalidOperationException("Denominator can't be 0");

        }
        /**
         * Finding the GCD
         */
        int gcd = Greatestcommondivisor(numerator, denominator);
        /**
         * removing the GCD from numer..and denom..
         */
        numerator = numerator / gcd;
        denominator = denominator / gcd;
        /**
         * setting values to the variables
         */
        this.numerator = numerator;
        this.denominator = denominator;

        // normalizing
        Normalize();

    }

    public Rational(int numerator):this(numerator, 1) {
        
    }

    public Rational() :this(0, 1){
        
    }

    /**
     * A private method to calculate the greatest common divisor of two numbers
     */
    private int Greatestcommondivisor(int x, int y) {
        if (y == 0)
            return x;
        return Greatestcommondivisor(y, x % y);
    }

    /**
     * method to add a rational number to the current number and returns it
     */
    public Rational Add(Rational b) {
        int num = (this.numerator * b.denominator)
                + (this.denominator * b.numerator);
        int den = this.denominator * b.denominator;
        Rational rational = new Rational(num, den);
        return rational;
    }

    /**
     * method to subtract a rational number from the current number and returns
     * it
     */
    public Rational Sub(Rational b) {
        int num = (this.numerator * b.denominator)
                - (this.denominator * b.numerator);
        int den = this.denominator * b.denominator;
        Rational rational = new Rational(num, den);
        return rational;
    }

    /**
     * method to multiply a rational number to the current number and returns it
     */
    public Rational Mul(Rational b) {
        int num = this.numerator * b.numerator;
        int den = this.denominator * b.denominator;
        Rational rational = new Rational(num, den);
        return rational;
    }

    /**
     * method to divide a rational number from the current number and returns it
     */
    public Rational Div(Rational b) {
        /**
         * Finding the recipocal of second number and multiplying it
         */
        b = b.Reciprocal();
        return Mul(b);
    }

    /**
     * method to return the reciprocal of a rational number
     */
    public Rational Reciprocal() {
        int newNumerator = this.denominator;
        int newDenominator = Math.Abs(this.numerator);
        if (this.numerator < 0) {
            newNumerator = 0 - newNumerator;
        }
        return new Rational(newNumerator, newDenominator);
    }

    public void Normalize() {
        /**
         * if denom is less than 0, making it positive and changing the sign of
         * numerator
         */
        if (denominator < 0) {
            // multiplying numerator and denominator with -1 to swap signs
            denominator *= -1;
            numerator *= -1;
        }
    }

    /**
     * method to return a string representation of a number
     */
    public override String ToString() {
        return numerator + "/" + denominator;
    }
    
    /**
     * method to display rational number in a/b form
     */
    public void DisplayRational(){
        Console.WriteLine(ToString());
    }
    
    /**
     * method to display the rational number in fractional form
     * allowing user to choose precision, or using a default value 2
     */
    public void DisplayAsFraction(int precision=2){
        double fraction=(double)numerator/denominator;
        Console.WriteLine(Math.Round(fraction,precision));
    }
}


//class to test the Rational class and methods
public class RationalTest {
    


    public static void Main(String[] args) {
        //creating two rational numbers and testing the methods
        Rational a = new Rational(2, 3);
        Rational b = new Rational(1, 2);
        Console.WriteLine(a + " + " + b + " = " + a.Add(b));
        Console.WriteLine(a + " - " + b + " = " + a.Sub(b));
        Console.WriteLine(a + " * " + b + " = " + a.Mul(b));
        Console.WriteLine(a + " / " + b + " = " + a.Div(b));

        Console.Write(a+" as Fraction: ");
        //displaying a as fraction with a precision of 4 digits after decimal point
        a.DisplayAsFraction(4);
        
        //waiting for a key press to quit, remove if not necessary.
        Console.WriteLine("\n\n\nPress any key to quit");
        Console.ReadKey();

    }

}

/*OUTPUT*/

2/3 + 1/2 = 7/6

2/3 - 1/2 = 1/6

2/3 * 1/2 = 1/3

2/3 / 1/2 = 4/3

2/3 as Fraction: 0.6667


Related Solutions

The following program will be written in JAVA. Create a class called complex performing arithmetic with...
The following program will be written in JAVA. Create a class called complex performing arithmetic with complex numbers. Write a program to test your class.                         Complex numbers have the form:                         realPart + imaginaryPart * i                                               ___                         Where i is sqrt(-1)                                                 Use double variables to represent data of the class. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should contain default values in...
9.6 (Rational Class) Create a class called Rational (separate the files as shown in the chapter)...
9.6 (Rational Class) Create a class called Rational (separate the files as shown in the chapter) for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private data of the class-the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it's declared. The constructor should contain default values in case no initializers are provided and should store the fraction in reduced form. For...
Task Create a class called Mixed. Objects of type Mixed will store and manage rational numbers...
Task Create a class called Mixed. Objects of type Mixed will store and manage rational numbers in a mixed number format (integer part and a fraction part). The class, along with the required operator overloads, should be written in the files mixed.h and mixed.cpp. Details and Requirements Finish Lab 2 by creating a Mixed class definition with constructor functions and some methods. The Mixed class should have public member functions Evaluate(), ToFraction(), and Simplify(). The Evaluate() function should return a...
Define a class called Rational for rational numbers. Arational number is a number that can...
Define a class called Rational for rational numbers. A rational number is a number that can be represented as the quotient of two integers. For example, /2, 3/4, 64/2, and so forth are all rational numbers.Represent rational numbers as two private values of type int, numfor the numerator and den for the denominator. The class has a default constructor with default values (num = 0,den = 1), a copy constructor, an assignment operator and three friend functions for operator overloading...
Task CPP Create a class called Mixed. Objects of type Mixed will store and manage rational...
Task CPP Create a class called Mixed. Objects of type Mixed will store and manage rational numbers in a mixed number format (integer part and a fraction part). The class, along with the required operator overloads, should be written in the files mixed.h and mixed.cpp. Details and Requirements Finish Lab 2 by creating a Mixed class definition with constructor functions and some methods. The Mixed class should have public member functions Evaluate(), ToFraction(), and Simplify(). The Evaluate() function should return...
Write a rational number class in C++. Recall a rational number is a rational number, composed...
Write a rational number class in C++. Recall a rational number is a rational number, composed of two integers with division indicated. The division is not carried out, it is only indicated, as in 1/2, 2/3, 15/32. You should represent rational numbers using two int values, numerator and denominator. A principle of abstract data type construction is that constructors must be present to create objects with any legal values. You should provide the following two constructors: one constructor to make...
Needed in C++ In this assignment, you are asked to create a class called Account, which...
Needed in C++ In this assignment, you are asked to create a class called Account, which models a bank account. The requirement of the account class is as follows (1) It contains two data members: accountNumber and balance, which maintains the current account name and balance, respectively. (1) It contains three functions: functions credit() and debit(), which adds or subtracts the given amount from the balance, respectively. The debit() function shall print ”amount withdrawn exceeds the current balance!” if the...
C++ HW Aim of the assignment is to write classes. Create a class called Student. This...
C++ HW Aim of the assignment is to write classes. Create a class called Student. This class should contain information of a single student. last name, first name, credits, gpa, date of birth, matriculation date, ** you need accessor and mutator functions. You need a constructor that initializes a student by accepting all parameters. You need a default constructor that initializes everything to default values. write the entire program.
Create a C# Application. Create a class object called “Employee” which includes the following private variables:...
Create a C# Application. Create a class object called “Employee” which includes the following private variables: firstN lastN idNum wage: holds how much the person makes per hour weekHrsWkd: holds how many total hours the person worked each week regHrsAmt: initialize to a fixed amount of 40 using constructor. regPay otPay After going over the regular hours, the employee gets 1.5x the wage for each additional hour worked. Methods: constructor properties CalcPay(): Calculate the regular pay and overtime pay. Create...
C++ make a rational class that includes these members for rational -private member variables to hold...
C++ make a rational class that includes these members for rational -private member variables to hold the numerator and denominator values -a default constructor -an overloaded constructor that accepts 2 values for an initial fraction -member fractions add(), sub(), mul(), div(), less(), eq(), and neq() (less should not return true if the object is less than argument) -a member function that accepts an argument of type of ostream that writes the fraction to that open output stream do not let...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT