Create
a four-function calculator for fractions so that each fraction is stored
internally as a variable of type struct fraction. Here are the formulas for the
four arithmetic operations applied to fractions:
Addition: a/b + c/d = (a*d + b*c) / (b*d)
Subtraction: a/b - c/d = (a*d - b*c) / (b*d)
Multiplication: a/b * c/d = (a*c) / (b*d)
Division: a/b / c/d = (a*d) / (b*c)
The
user should type the two fractions and an operator. The program should then
display the result and ask whether the user wants to continue.
SOLUTION:
#include<iostream.h>
#include<conio.h>
/////////////////////////////////////////////////////////////
Define Structures
////////////////////////////////////////////////////////////
struct
fraction
{
int nume,denom;
};
/////////////////////////////////////////////////////
Define Structure Variables
/////////////////////////////////////////////////////
fraction
f[2],rf;
void
main()
{
int i;
char dummychar,opr,ch;
do
{
clrscr();
/////////////////////////////////////////////////////////////////
Take Input
////////////////////////////////////////////////////////////////////
for(i=0;i<2;i++)
{
cout<<"Enter Fraction
"<<i+1<<": ";
cin>>f[i].nume>>dummychar>>f[i].denom;
}
cout<<"Enter Operator: "; cin>>opr;
//////////////////////////////////////////////////////////////////
Calculate rf
/////////////////////////////////////////////////////////////////
switch(opr)
{
case '+':
rf.nume=(f[0].nume*f[1].denom)+(f[0].denom*f[1].nume);
rf.denom=f[0].denom*f[1].denom;
break;
case '-':
rf.nume=(f[0].nume*f[1].denom)-(f[0].denom*f[1].nume);
rf.denom=f[0].denom*f[1].denom;
break;
case '*':
rf.nume=f[0].nume*f[1].nume;
rf.denom=f[0].denom*f[1].denom;
break;
case '/':
rf.nume=f[0].nume*f[1].denom;
rf.denom=f[0].denom*f[1].nume;
break;
}
//////////////////////////////////////////////////////////////////////
Output
/////////////////////////////////////////////////////////////////////
cout<<"\n"<<f[0].nume<<"/"<<f[0].denom<<opr<<f[1].nume<<"/"<<f[1].denom;
cout<<" ="<<rf.nume<<"/"<<rf.denom<<"\n"<<"If
you want to continue, press 'y' ";
ch=getch();
}
while(ch=='y' || ch=='Y');
getch();
}
OUTPUT:
0 comments: