Well, the answer to why you always get 0 is that dividing 2 integers will never give a non-integer. So 1/2 = 0. and 4/3 = 1. You could see the 'correct' output, at least of what you wrote, by changing line 23 of what you posted to
f=(float)n/d
, but then you'll see that the results aren't what you want. This is called an
explicit cast and makes
n be converted to a floating point number before being divided by
d. (A float divided by an int
will give a float.) More info about type-casting in C++ here:
http://www.cplusplus.com/doc/tutorial/typecasting/
For what you want to do, you're going to need to store the numerator and denominator separately all the way through. Once you have them, you should be able to reduce them if you want, or just display them unreduced. (You could do this already by changing line 24 of what you posted to
cout<<"Answer = "<< n << "/" << d << endl;
) If you're interested in reducing them, the
modulo mathematical operation might interest you. It returns the remainder after division, and in C++ is represented by a
%. Ex: 4%3 = 1, because the remainder of 4/3 is 1. 6%3 = 0, because the remainder of 6/3 is 0. And so on.
floating point numbers are useful, just not in the case of what you're trying to do. Hope this helps.