Quote:>I am trying to solve a problem out of Deitels' C++: HTP book, #6.7

>I need to add, multiply, divide, etc. rational numbers.

>i can't get the functions right.

>if anyone knows how to do this or has any sample code, please help me

>out.

Your code:

int common(int den1, int den2)

{

int search;

for(search=den2; search>0; search--)

{

if(((den1%search)==0) && ((den2%search)==0))

}

return search;

Quote:}

...clearly isn't going to work - whenever it finds a suitable common

denominator, it just throws it away and carries on, eventually always

returning zero...

What you want is something more like this, with the return statement

within your if block:

int common(const int den1, const int den2)

{

for(int search = den2; search > 0; search--)

{

if((den1 % search)==0 && (den2 % search)==0)

return search;

}

Quote:}

>void addRat(int n1, int n2, d) //n1, n2 are numerators, d is value

>{ //returned by common function

As for your addRat function, what are you actually trying to do? Add

two rational numbers? If so, you really need to pass in both numerators

and both denominators. However, I really can't help thinking the whole

exercise could be made better and you could learn more by writing a C++

class called Rational, with +,-,/,* operators. Your "common" function

would be a private member of your Rational class, and you'd expose

public arithmetic operators which act on the rational numbers

represented by objects of the Rational class. That way you could do

stuff like this:

Rational r1(1,3); // Declare r1 to be 1/3

Rational r2(5,23) // Declare r2 to be 5/23

Rational sum = r1 + r2; // Would set sum to be 1/3 + 5/23

cout << sum; // Would write the value out as 38/69

I'll leave you that class to write as an exercise.....*8)

Neil

--

===================================================================

Tel: 01293 454736 Mobile: 07931 164 346 Fax: 08700 520159

===================================================================