is there anyway to do it without a class? I'm taking a computer science intro class and we haven't really learned about classes yet so it would look weird if I used it. |
Of course there is, and the reason I referred to an earlier post is to show the various aspects involved which can be used any number of ways.
You can use classes, structs or neither of these. That choice is yours especially if you are not familiar with them.
The point of the class I referred to is it shows how to manipulate the two numerators and two denominators and, this is the crunch, the GCD function to cancel out common factors in the numerator and denominator.
In simple terms your inputs to the addition function ( from processing the overall input string ) are just 4 integers corresponding to the numerator and denominator of each fraction. Call them a,b, c & d. ie a/b + c/d Then calculate integers x and y which are the numerator and denominator of the answer.
So,
a/b + c/d = x/y just like on pencil and paper
Now, a/b + c/d = (a*d +c*b) /(b *d ) so we get x and y (Don't do the division, just get the values of x and y)
Next cancel factors (via GCD) of x and y and, bingo you have your fraction
cout << "answer = " << x << "/" << y << endl;
The missing GCD:
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
|
// GREATEST COMMON_DIVISOR
// https://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid.27s_algorithm
int Fraction::GCD( int aa, int bb)
{
int a = aa;
int b = bb;
int b_previous = 0;
// SORT NUMBERS
int temp = 0;
if (a < b)
{
temp = b;
b = a;
a = temp;
}
int remainder = a % b ;
if(remainder == 0)
return b;
while( remainder != 0 )
{
a = b;
b = remainder;
b_previous = remainder;
remainder = a % b;
}
return b_previous;
}
|