Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

ASSIGNMENT # 1

Create a class called Rational for performing arithmetic with fractions. Also write a main()
program to test your class.Use integer variables to represent the private data of the class—the
numerator and the denominator. Provide a constructor function that enables an object of this
class to be initialized when it is declared. The constructor should contain default values
incase no initializers are provided and should store the fraction in reduced form (i.e., the
fraction 2/4 would be stored in the object as 1 in the numerator and 2 in the denominator).
Provide public member functions for each of thefollowing:
a) Addition of two Rational numbers.
b) Subtraction of two Rational numbers.
c) Multiplication of two Rational numbers.
d) Division of two Rational numbers.
e) Printing Rational numbers in the form a/b where a is the numerator and b is the
denominator.
f) Printing Rational numbers in double floating-point format.

PROGRAM:
#include "stdafx.h"
#include<iostream>
using namespace std;
class Rational
{
private:
int num,den;
public:
Rational():num(1),den(2)
{}
void input()
{
cout<<"Num=";
cin>>num;
cout<<"den=";
cin>>den;
}
void add(Rational d1,Rational d2)
{
Rational d3,d4;
float d5;
{
d3.den=d1.den*d2.den;
d4.num=d1.num*d2.den;
d4.den=d2.num*d1.den;
d3.num=d4.num+d4.den;
}
d5=d3.num/d3.den;

cout<<d1.num<<"/"<<d1.den<<"+"<<d2.num<<"/"<<d2.den<<"="<<d3.num<<"/"<<d3.den<<endl;
cout<<d3.num<<"/"<<d3.den<<"="<<d5<<endl;
}
void Subtraction(Rational d1,Rational d2)
{
Rational d3,d7;
float d5;
{
d3.den=d1.den*d2.den;
d7.num=d1.num*d2.den;
d7.den=d2.num*d1.den;
d3.num=d7.num*d7.den;
}
d5=d3.num/d3.den;

cout<<d1.num<<"/"<<d1.den<<"-"<<d2.num<<"/"<<d2.den<<"="<<d3.num<<"/"<<d3.den<<endl;
cout<<d3.num<<"/"<<d3.den<<"="<<d5<<endl;
}
void mul(Rational d1,Rational d2)
{
Rational d3;
float d5;
{
d3.num=d1.num*d2.num;
d3.den=d1.den*d2.den;
}
d5=d3.num/d3.den;

cout<<d1.num<<"/"<<d1.den<<"*"<<d2.num<<"/"<<d2.den<<"="<<d3.num<<"/"<<d3.den<<endl;
cout<<d3.num<<"/"<<d3.den<<"="<<d5<<endl;
}
void div(Rational d1,Rational d4)
{
Rational d;
float d5;
d.den=d1.den*d4.num;
d.num=d1.num*d4.num;
d5=d.den/d.num;

cout<<d1.num<<"/"<<d1.den<<"+"<<d4.num<<"/"<<d4.den<<"="<<d.num<<"/"<<d.den<<endl;
cout<<d.num<<"/"<<d.den<<"="<<d5<<endl;
}
void print(Rational i,Rational l)
{
cout<<"fraction form of first object:"<<i.num<<"/"<<i.den<<endl;
cout<<"fraction form of second object:"<<l.num<<"/"<<l.den<<endl;
};
int _tmain(int argc, _TCHAR* argv[])
{
Rational u,o,e;
u.input();
o.input();
e.add(u,o);
e.Subtraction(u,o);
e.mul(u,o);
e.div(u,o);
e.print(u,o);
system("pause");
return 0;
}

You might also like