tags:

views:

111

answers:

5

what are some of the things i need to consider when designing this object this is all i can think of

int nominator
int denominator
int sign

this object can be used in a math operation

+1  A: 

Consider the behavior of the class. What operations do you want to be able to perform on this fraction class?

  • Create it - this means a constructor. So what arguments should the constructor take? 2 ints? 2 ints and a boolean for sign? The ints could carry signs too.
  • Add two fractions, subtract, multiply, divide - do you want these to be static methods or object methods [ aFraction.Add(anotherFraction) or Fraction.Add(aFraction, anotherFraction) ]. What do these methods return - a Fraction object? a float?
  • How do you compare two fractions are equal? If you want to do this without breaking encapsulation, then make sure you provide an equals method - Java and C# have a particular signature for the equals method.
Rohith
Re your second bullet, also consider providing overloads for the +, -, * and / operators. To support myFraction / 2, consider additional overloads with integer types, or implicit conversion. To support int i = (int)(frac / 2), consider explicit conversion to integral or floating point types.
itowlson
+2  A: 

Unless you use unsigned int and you are sure you don't want the denominator and numerator to contain signs, you should probably get rid of the third member (sign), as it is redundant.

Then it depends on the language you are using, you might want to overload some operators for this class (C++), or implement methods to compute the behaviour, like Rohith said.

rxin
+1  A: 

Consider the following multiplication problem:

2/3 * 3/4. The answer is 6/12, naively. But 1/2, intelligently. You'll need to take this into account to deal with equality.

Now, what about 2000000000/3000000000 * 3/4? If you use 32-bit ints to represent your numerator and denominator, you'll overflow if you do the naive computation first. Of course, if your language supports bignums, this is not so big a problem.

When you're reducing to lowest terms, don't forget to consider the sign of the result -- in general, decide pick one of the numerator or the denominator to be negative when representing negative rationals, and stick with it.

novalis
+1  A: 

You may also want a member function to output a decimal value, and a toString function so you can print numerator/denominator without extra effort.

There is a "boundary" case of sorts here, too - the denominator can't be zero or your value is undefined. Your constructor and any setters will need to respond to this possibility.

Frank DeRosa
+1  A: 

Chapter 2 in Timothy Budd's "Classic Data Structures In C++" has a very nice Rational class in C++. It includes all the points made here, including an implementation of GCD to normalize 6/12 into 1/2. Well worth reading.

duffymo