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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
/*
lab7_2.cpp
Program asks the user if they would like to add, subtract, multiply, or divide two fractions
User enters two fractions.
Program calculates the new fraction.
Inputs: n1, d1, n2, d2
Outputs: n3, d3
Process:
*/
# include <iostream>
using namespace std;
bool scanFraction(int &num, int &den);
int add(int n1, int d1, int n2, int d2, int &n3, int &d3);
int subtract(int n1, int d1, int n2, int d2, int &n3, int &d3);
int multiply(int n1, int d1, int n2, int d2, int &n3, int &d3);
int divide(int n1, int d1, int n2, int d2, int &n3, int &d3);
int calculate(int choice, int n1, int d1, int n2, int d2, int &n3, int &d3);
int main(){
int n1, d1, n2, d2, choice;
int n3;
int d3;
cout << "1: Add\n";
cout << "2: Subtract\n";
cout << "3: Multiply\n";
cout << "4: Divide\n";
cout << "0: Exit\n";
cin >> choice;
scanFraction(n1, d1);
scanFraction(n2, d2);
calculate(choice, n1, d1, n2, d2, n3, d3);
cout << "Your new fraction is " << n3 << "/" << d3 << endl;
return 0;
}
int getChoice(int &choice){
return choice;
}
bool scanFraction(int &num, int &den){
char slash;
cout << "Enter a fraction: ";
cin >> num >> slash >> den;
return slash == '/';
}
int add(int n1, int d1, int n2, int d2, int &n3, int &d3){
n3 = ((n1*d2) + (n2*d1)) / (d1* d2);
d3 = d1 * d2;
return n3 / d3;
}
int subtract(int n1, int d1, int n2, int d2, int &n3, int &d3){
n3 = (n1*d2) - (n2*d1);
d3= d1 * d2;
return n3 / d3;
}
int multiply(int n1, int d1, int n2, int d2, int &n3, int &d3){
n3 = n1 * n2;
d3= d1 * d2;
return n3 / d3;
}
int divide(int n1, int d1, int n2, int d2, int &n3, int &d3){
n3 = n1 * d2;
d3 = n2 * d1;
return n3 / d3;
}
int calculate(int choice, int n1, int d1, int n2, int d2, int &n3, int &d3){
switch(choice){
case '0':
exit(-1);
break;
case '1':
add(n1, d1, n2, d2, n3, d3);
break;
case '2':
subtract(n1, d1, n2, d2, n3, d3);
break;
case '3':
multiply(n1, d1, n2, d2, n3, d3);
break;
case '4':
divide(n1, d1, n2, d2, n3, d3);
break;
default:
break;
return choice;
}
}
|