question about adding two fractions

Hey all, I am new in learning the C++ language..
I have question about the program for adding two fractions..

Here is my code:
// adding two fractions

#include <iostream>
using namespace std;

int main()
{
float a;
float b;
float x;
float y;

// input

cout << "Enter numerator value of First fraction" << endl;
cin >> a;
cout << "Enter denominator value of First fraction" << endl;
cin >> b;

cout << "Enter numerator value of Second fraction" << endl;
cin >> x;
cout << "Enter denominator value of Second fraction" << endl;
cin >> y;



// Process

cout << "The Result is " << (a/b)+(x/y) << endl;

return 0;
}

The answer is given to me in decimal (when the fraction is added).. but i want it to give me the answer the fraction form.. I cant help it doing that..
We know that fractions like 2.25, 1.5, 1.25 are rational fractions so they can be converted in rational numbers like ( 4/1, 3/2 etc.. )
So, tell me a technique to do this..

thanks..




Last edited on
Why are storing integers as floats?

Also, can you write an example of how you would like to see the fraction formatted?

Third, I didn't know there was the program for storing fractions.

Fourth, if you want to really impress your teacher, use classes.

Finally, use code tags. [co de][/c ode] without the spaces.
Why are storing integers as floats?
Fractional fractions. Duh. :-)

Fourth, if you want to really impress your teacher, use classes.
Quiet, you.

The best way is to not compute the decimal floating point representation in the first place.
Instead of outputting a/b+x/y, output separately a*y+x*b and b*y. The result will not be simplified (for example, it could give 2/2, rather than 1/1).


a c a * d + c * b
--- + --- = ---------------
b d b * d
Last edited on
Well, then he could use operator overloading.
Topic archived. No new replies allowed.