0

I need to write a program that can calculate fractions using the operator that the user enters. I have different functions to reduce the fractions and find the greatest common denominator (which i'm not sure if i set them up correctly or not), and then I have the function calculate() to find the answer. I have to print out the final answer in fraction form and not decimal.

The problem I am having is that I don't know how to return num3 and den3 from calculate() back into the main function. If anyone could help I would very gracious. Thank you.

Here is my code so far:

/*Problem: Write a program to manipulate fractions. It allows for the addition, subtraction, multiplication, or division of fractions.
    Inputs:
    Outputs:
*/

#include <iostream>
using namespace std;

void calculate(int num1, int den1, int& num3, int& den3, int num2, int den2);
void reduce(int& num, int& den);
int gcd(int a, int b);

int main(){
    int num1, num2, den1, den2, add, sub, mult, div;
    int op, calc;
    int num3, den3;

    cout << "Enter the numerator of the first fraction" << endl;
    cin >> num1;
    cout << "Enter the denominator of the first fraction" << endl;
    cin >> den1;
    cout << "Enter the numerator of the second fraction" << endl;
    cin >> num2;
    cout << "Enter the denominator of the second fraction" << endl;
    cin >> den2;
    cout << "Enter a 1 for addition, 2 for subtraction, 3 for multiplication, or 4 for division" << endl;
    cin >> op;
    calculate(op, num1, den1, num3, den3, num2, den2);
    cout << "The answer using option: " << op << endl;
    cout << "is " << num3 << " / " << den3 << endl;



    return 0;
}

void calculate(int op, int num1, int den1, int& num3, int& den3, int num2, int den2){
    if(op==1){
        num3 = num1 + num2;
        den3 = den1;
    }
    else if(op==2){
        num3 = num1 - num2;
        den3 = den1;
    }
    else if(op==3){
        num3 = num1 * num2;
        den3 = den1 * den2;
    }
    else if(op==4){
        num3 = num1 * den2;
        den3 = num2 * den1;
    }
}

void reduce(int& num, int& den){
    int reduced;
    reduced = gcd(num, den);
    num = num/reduced;
    den = den/reduced;

}

int gcd(int a, int b){
    int divisor=1, temp;

    while(b!= 0 || b>a){ 
        temp = a % b; 
        a = b; 
        b = temp = divisor; 
    }
    while(a!=0 || a>b){
        temp = b % a;
        b = a;
        a = temp = divisor;
    }

    return divisor;
}
4

2 に答える 2