1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
|
/*main - calls the menu function and gets back the selection; and if the selection is not to quit, it then reads two fractions and passes them to the perform function.
menu - prints the menu and returns the selection to main.
perform - receives the selection and two fractions from main, performs the operation and passes the resulting fraction to reduce function.
reduce - receives the fraction from perform, reduces it and passes the reduced fraction to print for printing.
print - receives the reduced fraction from reduce and prints it.
*/
#include <iostream>
#include <ctime>
using namespace std;
int menu_f();
void perform_f(int,int,int,int,int);
void reduce_f(int &,int &);
void print_f(int &, int &);
int main()
{
int num1,den1,num2,den2,choice;
char slash;
choice = menu_f();
if(choice==5)
{
system("pause");
exit(0);
}
else
{
cout<<"Enter two fractions (e.g.: 1/2 3/4): ";
cin>>num1>>slash>>den1>>num2>>slash>>den2;
}
perform_f(num1,den1,num2,den2,choice);
system("pause");
}
//*********************************************************\\
int menu_f()
{
int choice;
cout<<"\nSelect an operation from the following menu:"
<<"\n1.Add"
<<"\n2.Subtract"
<<"\n3.Multiply"
<<"\n4.Divide"
<<"\n5.Quit";
cout<<"\nEnter Selection: ";
cin>>choice;
while(choice<=0 || choice>5)
{
cout<<"Invalid entry selected! Please re-enter selection:";
cin>>choice;
}
return choice;
}
//******************************************************************//
void perform_f(int num1, int den1, int num2, int den2,int choice)
{
int snum;
int sden;
if(choice==1)
{
snum=(num1*den2)+(num2*den1);
sden= den1*den2;
}
if(choice==2)
{
snum=(num1*den2)-(num2*den1);
sden=den1*den2;
}
if(choice==3)
{
snum=num1*num2;
sden=den1*den2;
}
if(choice==4)
{
snum=(num1*den2);
sden=(num2*den1);
}
reduce_f(snum, sden);
}
//********************************************************************//
void reduce_f(int &snum, int &sden)
{
for(int i=1;i<=sden;i++)
if(snum%i==0 || sden%i==0)
{
snum=snum/i;
sden=sden/i;
}
print_f(snum,sden);
}
//*******************************************************************//
void print_f(int &snum, int &sden)
{
char slash='/';
cout<<endl<<snum<<slash<<sden<<endl;
}
|