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
|
#include <iostream>
void Reduce ( int *rout );
void PrintFraction ( int *out );
void AddFraction ( int *fa , int *fb , int *out )
{
out[1] = (fa[1] * fb[2]) + (fa[2] * fb[1]);
out[2] = fa[2] * fb[2];
out[0] = fa[0] + fb[0];
Reduce ( out );
}
void Reduce ( int *rout )
{
int sum = 0, val = 0;
if (rout[1] >= rout[2])
{
sum = rout[1]/rout[2];
rout[0] += sum;
rout[1] -= (rout[2] * sum);
}
for ( sum = rout[1]; sum > 1; sum --)
{
if ( rout[1] % sum == 0 && rout[2] % sum == 0 )
{
val = sum;
break;
}
}
if (val > 1)
{
rout[1] = rout[1] / val;
rout[2] = rout[2] / val;
}
}
void PrintFraction ( int *out )
{
std::cout << out[0] << " " << out[1] << "/" << out[2] << std::endl;
}
int main()
{
int fractiona[3] = { 0 , 1 , 3 };
int fractionb[3] = { 0 , 2 , 5 };
int result[3] = { 0 , 0 , 0 };
int test[3] = { 0 , 9 , 33 };
int test2[3] = { 0 , 10 , 25 };
AddFraction( fractiona , fractionb , result );
PrintFraction ( result );
Reduce( test );
PrintFraction ( test );
Reduce( test2 );
PrintFraction ( test2 );
return 0;
}
|