0% found this document useful (0 votes)
6 views2 pages

Rational Number

The document describes a Java class named RationalNumber that represents rational numbers with a numerator (p) and a denominator (q). It includes constructors for initializing these values, methods for printing the rational number, calculating its decimal value, simplifying it, and finding its reciprocal. The class also contains example outputs for each method to demonstrate functionality.

Uploaded by

panav.golyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Rational Number

The document describes a Java class named RationalNumber that represents rational numbers with a numerator (p) and a denominator (q). It includes constructors for initializing these values, methods for printing the rational number, calculating its decimal value, simplifying it, and finding its reciprocal. The class also contains example outputs for each method to demonstrate functionality.

Uploaded by

panav.golyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

File: Untitled Document 1 Page 1 of 2

/**
* Write a description of class RationalNumber here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class RationalNumber
{
int p;//This variable stores the numeric value of the numerator
int q;//This variable stores the numeric value of the denominator

//This is a default constructor that assigns the value to the instance variables
public RationalNumber()
{
int p = 0;
int q = 1;
}

//This is a parameterised constructor that assigns the value to the instance variables
public RationalNumber(int p , int q)
{
this.p = p;
if(q >= 1)
this.q = q;
else
this.q = 1;
}

//This function prints the rational number


void print()
{
System.out.print("The Rational number is " + p +"/" + q);
/**
* Output:
* The Rational number is 2/3
*/
}

//This function returns the decimal value of the given rational number
float decimalValue()
{
float f = ((float)p) / q;
System.out.print(f);
return f;
/**
* Output:
* 0.6666667
*/
}

//This function simplifies the rational number by the gcd of the numerator and
denominator
void simplify()
{
int a = Math.min(p , q);

for(int gcd = 1 ; gcd<= a ; gcd++)


{
if(p%gcd == 0 && q%gcd ==0)
{
p = p / gcd;
q = q / gcd;
}
}
System.out.print(p + "/" + q);
File: Untitled Document 1 Page 2 of 2

/**
* Output:
* 2/3
*/
}

//This function gives the reciprocal of the rational number


RationalNumber reciprocal()
{
RationalNumber reciprocal = new RationalNumber();
reciprocal.p = q;
reciprocal.q = p;
System.out.print(reciprocal.p + "/" + reciprocal.q);
return reciprocal;
/**
* Output:
* 3/2
*/
}

You might also like