Note that one advantage of the OOP approach is that an entire
class can be used, without modification, in a different program. Use the
fraction class from Exercise 11 in a program that generates a multiplication
table for fractions. Let the user input a denominator, and then generate all
combinations of two such fractions that are between 0 and 1, and multiply them
together. Here’s an example of the output if the denominator is 6:
|
1/6
|
1/3
|
½
|
2/3
|
5/6
|
1/6
|
1/36
|
1/18
|
1/12
|
1/9
|
5/36
|
1/3
|
1/18
|
1/9
|
1/6
|
2/9
|
5/18
|
½
|
1/12
|
1/6
|
1/4
|
1/3
|
5/12
|
2/3
|
1/9
|
2/9
|
1/3
|
4/9
|
5/9
|
5/6
|
5/36
|
5/18
|
5/12
|
5/9
|
25/36
|
SOLUTION:
#include "stdafx.h"
#include "iostream"
#include "math.h"
using namespace std;
/////////////////////////////////////////////////////////////////////////////////////////
class fraction
{
private:
int
num, den;
public:
fraction
( ): num(0), den(1)
{/*Empty
Body*/}
fraction
(int n, int d): num(n), den(d)
{/*Empty
Body*/}
int
get_den ( )
{
cout << "Enter Denominator:
";
cin >> den;
cout << endl;
return den;
}
void
show_F ( ) const
{
cout << "\t"
<< num << "/" << den;
}
fraction
gen_pairs ( int i, int k )
{
for(int
j=1;j<den;j++)
{
fraction
temp;
int
de = 0, nume = 0 ;
num
= i;
nume
= num*k;
de
= den*den;
temp
= lowterms(nume,de);
return
fraction(temp.num,temp.den);
}
}
fraction
lowterms (int, int);
};
//---------------------------------------------------------------------------------------
fraction fraction::lowterms ( int n, int d )
{
long
tnum, tden, temp, gcd;
tnum =
labs(n);
tden =
labs(d);
if(tden==0
)
{
cout << "Illegal fraction:
division by 0";
exit(1);
}
else if(
tnum==0 )
{
n=0;
d = 1;
exit(1);
}
while(tnum
!= 0)
{
if(tnum
< tden)
{
temp=tnum;
tnum=tden;
tden=temp;
}
tnum
= tnum - tden;
}
gcd =
tden;
n = n /
gcd;
d = d /
gcd;
return
fraction(n,d);
}
/////////////////////////////////////////////////////////////////////////////////////////
void main( )
{
int
denom;
fraction
frac1,frac2[5];
denom =
frac1.get_den( );
for(int
j=1;j<denom;j++)
{
for(int
i=0;i<denom-1;i++)
{
frac2[i]=frac1.gen_pairs(i+1,j);
frac2[i].show_F(
);
}
cout
<< endl;
}
system("pause");
}
OUTPUT:
0 comments: