我需要编写一个程序,可以使用用户输入的运算符计算分数。我有不同的函数来减少分数并找到最大公分母(我不确定我是否正确设置它们),然后我有函数 calculate() 来找到答案。我必须以分数形式而不是小数形式打印出最终答案。
我遇到的问题是我不知道如何将 num3 和 den3 从 calculate() 返回到主函数。如果有人可以帮助我会非常亲切。谢谢你。
到目前为止,这是我的代码:
/*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;
}