Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Exercise Write a class Rational that encapsulates the concept of a rational number. Knowing that a rational number consists of a numerator and a denominator
Exercise Write a class Rational that encapsulates the concept of a rational number. Knowing that a rational number consists of a numerator and a denominator (both integer numbers). Detailed Requirement Your class should include three constructors (default, with 2 integer parameters, with a Rational parameter), set and get methods, toString() and equals) methods It should also include public methods for performing arithmetic operations (add, subtract, multiply and divide) The default constructor sets the numerator to 0 and the denominator to 1 The toString() method returns a string in the form "numerator/denominator". Notice that you should not allow the denominator to be equal to zero; in such a case you display an error message and set the rational number to its default value (i.e. 0/1) Exercise 2: (To be submitted on Moodle) Modify the constructors and any other method as needed, in such a way to keep the denominator always >0. For example the rational numbers (5/-6, -5/-6) should be changed to (-5/6 and 5/6 respectively) Add an internal method called normalize) that keeps the rational number in its minimal form For example, if the initial rational number is (45/25) the normalized rational number will be (9/5) and if the initial rational number is (45/15) the normalized rational number will be(3/1) To do this you have to divide both the numerator and denominator bytheir Greatest Common Divisor (gcd). You may use the Euclid algorithm for calculating the gcd Euclid's algorithm can be defined as follows: Let m and n represent the numerator and denominator respectively Divide m, if the remainder (r) is O then the gcd is n, otherwise save n in m and r in n and repeat until r =0
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started