Answered You can hire a professional tutor to get the answer.
Hi so Im creating a fraction calculator that also finds the gcd. My problem is that everytime I do the addition operator it comes out different from...
Hi so Im creating a fraction calculator that also finds the gcd. My problem is that everytime I do the addition operator it comes out different from what I expect.
My code is below:
#include <iostream>
using namespace std;
double gcd (int, int);
int main (){
char op, slash, repeat;
int num1, den1, num2, den2, resNum1, resNum2, big, small, ans;
do{
cout << "Enter the first fraction: ";
cin >> num1 >> slash >> den1;
while (den1 == 0){
cout << "Denominators cannot be equal to zero. Please reenter entire fraction with valid input: ";
cin >> num1 >> slash >> den1;
};
cout << "Enter operation: ";
cin >> op;
cout << "Enter the second fraction: ";
cin>> num2 >> slash >> den2;
while (den2 == 0){
cout << "Denominators cannot be equal to zero. Please reenter entire fraction with valid input: ";
cin>> num2 >> slash >> den2;
};
switch (op){
case '+':
resNum1 = (num1*den2 + num2*den1);
resNum2 = (den1*den2);
if (resNum1 > resNum2){
big = num1;
small = num2;
}
else {
small = resNum1;
big = resNum2;
}
ans = gcd (small, big);
cout << resNum1/ans << "/" << resNum2/ans;
break;
case '-':
resNum1 = (num1*den2 - num2*den1);
resNum2 = (den1*den2);
if (resNum1 > resNum2){
big = num1;
small = num2;
}
else {
small = resNum1;
big = resNum2;
}
ans = gcd (small, big);
cout << resNum1/ans << "/" << resNum2/ans;
break;
case '/':
resNum1 = (num1*den2);
resNum2 = (num2*den1);
if (resNum1 > resNum2){
big = num1;
small = num2;
}
else {
small = resNum1;
big = resNum2;
}
ans = gcd (small, big);
cout << resNum1/ans << "/" << resNum2/ans;
break;
case '*':
resNum1 = (num1*num2);
resNum2 = (den1*den2);
if (resNum1 > resNum2){
big = num1;
small = num2;
}
else {
small = resNum1;
big = resNum2;
}
ans = gcd (small, big);
cout << resNum1/ans << "/" << resNum2/ans;
break;
default: break;
}
do{
cout << "nContinue? (y/n): ";
cin >> repeat;
} while (repeat != 'y' && repeat != 'Y' && repeat != 'n' && repeat != 'N');
} while (repeat == 'y' || repeat == 'Y');
return 0;
}
double gcd (int small, int big){
int rem;
rem = big%small;
while (rem != 0){
small = rem;
rem = big%rem;
}
return (small);
}