JAVA
Rational Numbers
Create a Rational number class in the same style as the Complex number class created in class. That is, implement the following methods:
You must also provide a Main class and main method to fully test your Rational number class.
class Rational
{
private int num;
private int den;
//default constructor
Rational()
{
num = 0;
den = 1;
}
//parameterize constructor
Rational(int n, int d)
{
num = n;
den = d;
}
//method to add two rational number
public Rational add(Rational r)
{
Rational t = new Rational();
t.num = num * r.den + den * r.num;
t.den = den * r.den;
return t;
}
//method to subtract two rational number
public Rational sub(Rational r)
{
Rational t = new Rational();
t.num = num * r.den - den * r.num;
t.den = den * r.den;
return t;
}
//method to multiply two rational number
public Rational mul(Rational r)
{
Rational t = new Rational();
t.num = num * r.num;
t.den = den * r.den;
return t;
}
//method to divide two rational number
public Rational div(Rational r)
{
Rational t = new Rational();
t.num = num * r.den;
t.den = den * r.num;
return t;
}
//method to print the rational number
public String toString()
{
return num + "/" + den;
}
}
public class Main
{
public static void main(String[] args)
{
//create object
Rational r1 = new Rational(3,
5);
Rational r2 = new Rational(2,
7);
Rational r3 = new Rational();
//method calling and display result
r3 = r1.add(r2);
System.out.println(r1.toString()+"
+ "+r2.toString()+" = "+r3.toString());
r3 = r1.sub(r2);
System.out.println(r1.toString()+"
- "+r2.toString()+" = "+r3.toString());
r3 = r1.mul(r2);
System.out.println(r1.toString()+"
* "+r2.toString()+" = "+r3.toString());
r3 = r1.div(r2);
System.out.println(r1.toString()+"
/ "+r2.toString()+" = "+r3.toString());
}
}
OUTPUT:
3/5 + 2/7 = 31/35
3/5 - 2/7 = 11/35
3/5 * 2/7 = 6/35
3/5 / 2/7 = 21/10
Get Answers For Free
Most questions answered within 1 hours.