I've just started learning c++ on my own and am at a very basic level. I was working a problem in my book where I need to add two fractions and output the sum. Unfortunately, when I tried simple sets of fractions I constantly get zero as the sum. This is probably an issue with the way the numbers are being stored but I can't come up with a solution. Could someone please help? Thank you.
#include <iostream>
using namespace std;
int main ()
{
int w, x, y, z;
cout << "What are the two numerators? ";
cin >> w >> x;
cout << "What are the two denominators? ";
cin >> y >> z;
cout << "The sum of the two fractions is " << (w/y) + (x/z) << endl;
return 0;
}
That's because x y z w are integers and for integers 2/3 = 0 (they round down).
One solution would be to use floats.
A more appropriate one would be to output the sum as a fraction (cout << something << " / " << something_else;). I bet you can figure out what the something and something_else are.