> For this assignment, you are to write a C++ program which will read in rational numbers using the following convention (

For this assignment, you are to write a C++ program which will read in rational numbers using the following convention (

Posted at: 2014-12-18 
Have you studied struct and/or class types yet? One of those would be ideal for representing a rational number; and a proper class with constructors and operator overloads would be best in terms of making a useful rational number class.

If not, then I guess you're going to use local or global variables. Just follow the rules of arithmetic:

(a/b) + (c/d) = (ad + bc) / (bd)

(a/b) - (c/d) = (ad - bc) / (bd)

(a/b) * (c/d) = (ac) / (bd)

(a/b) / (c/d) = (ad) / (bc)

In each case, you'll want to reduce the result fraction by dividing out the greatest common factor of the numerator and denominator. Write a support function:

void reduce( int &p; int &q );

....that will (a) die with an error message if q is zero, (b) reduce to p==0, q==1 if p was 0 on entry, else (c) compute r as the greatest common factor of p and q, then reduce to (p/r) / (q/r).

Hint: This function can just return, doing nothing, as a "stub" if you want to work on your user interface and arithmetic first. Then, when you're getting 1/6 + 1/10 = 16/60 and (1/6) / (1/10) = 10/6 correctly, then coding the reduce function will fix the results for all of your functions at once.

Personally, I'd write gcf() first, using Euclid's algorithm (every programmer that does any computation with integers should know this one), test it in a separate main program, and then the coding of reduce() is a breeze.

Wikipedia's article on Euclid's Algorithm has pseudocode for computing gcf(a,b) in the simple case. Their mod function is the same as the % operator when a and b are both positive. The code will work when b is 0, but not when a is 0 or either a or b is negative. You'll want to add a check for these cases:

gcf(a,b) = gcf(|a|, |b|) ... remove minus signs

gcf(0,b) == b

gcf(a,0) == a (already in their code)

See: http://en.wikipedia.org/wiki/Euclidean_a...

50 / 12 If in the code two integers n1 and d1 were used, after reading in the above from cin n1 would be set to 50 and n2 would be set to 12.

(As a hint you can read the forward slash (/) into any arbitrary char data type.) Your program will prompt the user for two rational numbers. Your program will then display the following menu for the user:

1. ADDITION 2. SUBTRACTION 3. MULTIPLICATION 4. DIVISION If the user presses (1), the two rational numbers are added together. If the user presses (2) the two rational numbers are subtracted from each other. If the user presses (3) the two rational numbers are multiplied together. If the user presses (4) the two numbers are divided. After the answer is shown to the user, the user is prompted if he/she would like to run the program again.