jon smith wrote: |
---|
How would i read in the numerator and denominator? |
jon smith wrote: |
---|
Also, im pretty sure the output is supposed to be in fractions too.(except the conversion function) i am really confused as to how to do that, especially when adding. |
L B wrote: |
---|
Yes, you read in the numerator, then read the slash into a char (which you will not use), then read in the denominator. |
It's all just basic steps which you already know. You just need to put them together. The numerator and denominator are of type
int
. The slash is of type
char
. Just define separate variables for each. As LB has said, you don't use the contents of the slash, but you do need to read it.
If the output is supposed to be in the form of a fraction, then you will need to keep the number in the form of a fraction the whole way through the program. In order to simplify that, you might use a container to group these related values together.
Here I show the two different ways. I definitely recommend the use of the struct, though you can manage without if you wish.
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
|
#include <iostream>
using namespace std;
struct fraction {
int numer;
int denom;
};
int main()
{
const char slash = '/';
char dummy;
// either do this
int numer;
int denom;
cout << "enter a fraction a/b: " << endl;
cin >> numer >> dummy >> denom;
// or do this
fraction A;
cout << "enter a fraction a/b: " << endl;
cin >> A.numer >> dummy >> A.denom;
// output each
cout << "first: " << numer << slash << denom << endl;
cout << "second: " << A.numer << slash << A.denom << endl;
}
|
As for adding or multiplying fractions, just use the rules which you learned at school. For example
2/3 + 5/7 = (2*7 + 5*3) / (3 * 7)
and so on.
There is one refinement which you might want to add.
1/2 + 3/4 = 5/4 but if you just follow the rules , you would get 10 / 8.
Thus you may want to simplify the result by dividing numerator and denominator by their largest common factor.