I'm trying to print the output of the function after my values are sent to the function. The cout statement needs a string but I'm not sure how I can return a string from my reduce_fraction function while keeping the math correct. In my add_fraction function, you'll see that I simply want to print the added fraction then the reduced fraction right below it. The compiler returns no errors but the output just shows the "Improper Fraction" answer.
#include <iostream>
#include <string>
using namespace std;
void reduce_fraction (int top, int bottom)
{
for (int i = top * bottom; i > 1; i--) {
if ((top % i == 0) && (bottom % i == 0)) {
bottom /= i;
top /= i;
}
}
}
void add_fraction (int numerator, int numerator2, int denominator, int
denominator2)
{
int top;
int bottom;
top = numerator2 * denominator + denominator2 * numerator;
bottom = denominator2 * denominator;
cout << "Improper Fraction -> ";
cout << top << "/" << bottom << endl;
cout << "Simplified Fraction -> ";
reduce_fraction(top, bottom);
}
int main()
{
int numerator;
int denominator;
int numerator2;
int denominator2;
char operation;
cout << "Input the numerator: ";
cin >> numerator;
cout << "Input the denominator: ";
cin >> denominator;
cout << "Input the numerator2: ";
cin >> numerator2;
cout << "Input the denominator: ";
cin >> denominator2;
cout << "Input the operation: ";
cin >> operation;
if (operation == '+'){
add_fraction(numerator, numerator2, denominator, denominator2);
}
return 0;
}
Use reference to reflect the changes in top
and bottom
and print those in your add_fraction
function after calling reduce_fraction
void reduce_fraction ( int & top, int & bottom)
{ ~~~ ~~~
//...
}
Then,
reduce_fraction(top, bottom);
cout << top << "/" << bottom << endl;