Link to home
Start Free TrialLog in
Avatar of katdude
katdude

asked on

How do you add fractions in C++

I am writing a program that has to add, and multiply fractions.

I would like to prompt the user to enter 2 fractions i.e. 1/2 3/4

then prompt the user to choose A for add, or M to multiply them,
then

have the result come out in fraction form, and its decimal equivelent with it on the same line.

 I am having trouble with this, does anyone know how to help? even with just part of it.? if you give me a really good answer i'll up the points

Avatar of cwrea
cwrea
Flag of Canada image

Since this sounds like a homework problem, I'm willing to offer some general guidance, but no code:

Create a class that stores the fractions in its two integral parts, the numerator and denominator.  You'll need a constructor that takes two arguments, one for each of numerator and denominator.

Add methods to the class that can add one fraction to another (by doing the appropriate conversion to a common denominator) and another method to the class that can multiply the fractions.  Finally, add a method that returns the floating point equivalent of the fraction.  Write a main() routine that performs the input, construction, etc.

You can use operator overloading and other techniques if you want to be fancy, but it really isn't necessary.  But I certainly would recommend taking the approach of creating a Fraction class.

Oh, you may need a third integral part to represent a whole number should the addition or multiplication overflow; although you could use the numerator to store this info too but you'd end up with an improper fraction (e.g. 57/32)


Avatar of nietod
nietod

We cannot provide answers to school assignments.  That is grounds for removal from this site.  (for both you and the experts involved.)  We can provide only limitied help in accademic assignments.    We can answer specific (direct) questions, like you might ask your teacher.  We can review your work and post suggestions, again, like your teacher might do.

Do you have specific questions?
Do you have any work on this (incomplete even) that we can review?
You can probably think this out for yourself!!

Change (or convert) the fraction into a float type (or that kind of representation) and then add, subtract, multiply, etc.

Things may look confusing and bewildering at the beginning (it happens to all of us when starting out), but be calm and methodical, look through the language manual and try to make sense of what's written.  Then afterwards (even if everything is not clear), do some experimenting and you might just be surprised at how easy matters and events begin to unfold.  If after you've done all this and still find yourself stuck, come back and we'll help you get back in the clear.

ITM, good luck, and may success be with you!!
No offense, try, but that does not seem like a good idea.  floats are not good at representing fractions--like 1/3 for example. so while you can convert the fraction to float converting back is nearly impossible-because the loss of accuracy makes it impossible to say what exact fraction the approximate float represents.

Besides, this is a course on data structures, this suggest the problem should be handled with a data structure
Hi, this is only general info for you.

It's easy to experiment. Just try it out. Start from simple, and move on to harder code. If any of the stages is problematic, post it here with your code.

We will all be glad to help someone who is really trying, to proceed.
We cannot simply give you the code.

I suppose it is enough to explain what is needed. (Crash course in C++ follows:) I'm expecting you heard these "buzzwords", and I'm only helping you put it together.
An example with code (not directly related to your question) in the following comment.

A. Typically in C++ there are "instances" (or objects) of "classes" (types of objects).

B. Your program (the "main" function) would typically make 3 instances of a "Fraction".
The first two being the input, and the last being the sum.
For example: a, b, and c.
When "methods" (the functions of the class) are run it is done by using the dot:
For example: a.doSomething();  
or: b.doSomethingElse();

C. For this to work you would have to define (and "declare") a class called Fraction.
The class name is typically written with a capital letter.
The class would typically have data, which are variables of the class.
The class would typically have methods,
which are functions of the class.

D. If you are an OO fanatic, the data would be private (can be accessed only by the class methods, and not directly by outside methods such as methods in the main function, of of other classes).
For each variable you would need a set and get function.
See the sample code.

E. Typically the class takes care of the functions on it.
For example multiplying two fractions would be done by taking one instance, and using it's "multiply" method, with the second fraction as parameter.
c = a.multiply(b);

F. In an advanced setting the class takes care of "operators" so even the + and * would be supported. (In your case just an M and A are used so I won't talk about "operator overloading" much).
For example multiplying two fractions would be done by writing: c = a * b;

G. Because C++ language allows you to make all kinds of mistakes, you must check that your data is valid.
(So if you input letters instead of numbers, instead of the program crashing it nicely tells you you entered the wrong kind of data and gently asks you to enter the correct kind of data).
This is called error checking.
There are several ways to achieve this.

H. You need a "user interface" part of your code. In homework assignments it's usually just a section at the beginning of the "main" function, telling you to please enter this, then that.
You would put the input into the instances.
Usually using "C++ streams".
Something like:
  cout << "now enter param3";
  cin >> param3;

I. Since all your params are ints there is no need to "allocate memory".
When it comes to words and sentences or anything that's not a built in "type" would need extra code and checking for "runtime mistakes".
Example: forget it...

J. I suppose you didn't learn pointers,
so won't go in to that either, but just suffice to say there's a whole field of class pointer creation and usage not covered here.
For example:
 Monster* pMonst = new Monster(5,1);
 Monster->eat(KIDS,3);

Enjoy.

Moshe
I was making reference only to the mathematical aspect of the action.  I recognized it to be a data structure issue, but since the questioner wanted to know how addition, multiplication (etc.) can be done (him/her starting out with fraction), conversion seemed the first step.  (Being mindful that one thing usually lead up to another.  Data structure would come later.)

Mathematically, you can convert ANY representation from one form to another:  decimal to fraction, and vice versa, exponents, logarithm, etc.  Mathematically, it can be done.

With regards to accuracy, it's a matter of how many decimal places one wants to carry the fractional part of the expression.
Monster* pMonst = new Monster(5,1);
Monster->eat(KIDS,3);

------------------------------------

"mflam", I think you got your pointer mixed up a little there!
Avatar of ozo
> that does not seem like a good idea.  floats are not good at representing fractions--like 1/3 for example.
It may be suitable for the "and its decimal equivelent with it on the same line" part of the problem.  
and could let katdude get started on the code.

(trying to convert back to an approximate fractional representation would be another interesting problem, but not necessary for this task)
// some c++ code snippets

// b. in the main...
Monster a(3,2);
Monster b(7,5);
Monster c;
c = a.kiss(b);

// c1. declaring the class in the h file
class Monster
{
  public: // this is not typical...
  // member vars
  int m_Heads;
  int m_Toes;
 

  // Typically "public:" comes here.

  // methods
  //   The kiss method returns the
  //   number of our instances' heads
  //   devided by the number of heads
  //   of the monster in the parameter
  Monster kiss(Monster m);
};

//c2. Defining (cpp file) the methods
  // returns  class    method  params
  // -------  -------  ------  ------
  Monster     Monster::kiss( Monster m)
  {
     // first check that we don't make
     // a nonzero devision
     if (0 == m.m_Heads)
     {
        cout << "problem kissing";
        return 0;
     }  
     return Heads /(m.Heads);
  }

//d. set and get  
  // this would be done if you declared
  // the vars "private:"
  // You would declare the following
  // in an H file, and then
  // add for each var:
  void Monster::setHeads(int newVal)
  {
     Heads = newVal;
  }
 
  int Monster::getHeads(
  {
     return Heads;
  }

  // and in the main you wouldn't be
  // able to just write: a.Heads = 5;
  // you would need to write:
  a.setHeads(5);
  // but your kiss() method needs no
  // change because it's in the class.

e. See the kiss function above.

f. If you ask, I'll point you to code
   in the h files that come with your
   compiler.

g. See the "check" in the kiss method.
   You would typically put code like this in the "User Interface" section.

h. snippet from user interface:
  int x;
  cout << "now please enter heads";
  cin >> x;
  if (x > 3) // ... take care of error
  .... etc.. etc. etc.
  a.setHeads(x);

i,j. Some other time.

Enjoy, Moshe






Yup try, your correct.
Thanks,
I meant:

pMonst->eat(KIDS,3);
Sorry cwrea,

I just saw your comment which is more consice and better phrased...
I was using the beta, and did not see your comment there. (Perhaps skipped it).

Moshe
katdude, how would you add to fractions if you'd do it manually. Take note of every step and try to implement these steps in your code.
ASKER CERTIFIED SOLUTION
Avatar of sumant032199
sumant032199
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sumant, I think this "answer" and the "answer" question about postfix processing are inappropriate.  You aren't providing much of practicle value.  You've touched on one small issue in the problem out of many. We don't even know if that is an area where katdude is having problems or not.  Just as in the postfix question, you've ignored the important and difficult parts of the question in order to "answer" one one small part for which there is no indication there is a problem.