4 5 + 3 +is the same as:
4 + 5 + 3in infix notation (what we normally use). The really cool thing about RPN calculators is that you don't ever need parenthesis. The order of the operators always determines which comes first. Consider:
(5 + 3) * 2is the same as
2 5 3 + *pretty neat, no?
This assignment has two main parts. First is the rational number class, and second is the stack. Then of course is using it, but that is pretty easy. I would reccommend getting your rational number class working before going on to the rest. Use some test mains for that.
In the sample code you will notice a pretty cool function to allow you to output a rational number just like any other. You will need to overload a number of other operators (like + - etc...) in order to use your Rational number class like any other.
The rational number should always be in most reduced form. This is something that should not happen very often. It can be kind of expensive. Make sure you reduce your rational number efficiently. You may want to do it iteratively first. If there is a tricky part to the assignment this is it. One possible method of reducing the fraction utilizes Euclid's method of finding the greatest common denominator. Euclid stated around 300 BC that:
gcd(a,b) = gcd(b, a mod b)The modulus operator in c++ is %. You should make it work first then try to make it efficient. e.g. finish the assignment with this part being recursive then come back and make it iterative.
One last function you might want is one which will return the decimal equivilent, if you want that functionality in your calculator.
Rational strtorat(const char *input)
{
int totalNumerator = 0;
int totalDenominator = 0;
int i = 0;
char ch = input[i];
while (ch != 0 && ch != '/')
{
totalNumerator *= 10;
totalNumerator += (ch - '0');
i++;
ch = input[i];
}
if (ch == '/')
{
i++;
ch = input[i];
while (ch != 0)
{
totalDenominator *= 10;
totalDenominator += (ch - '0');
i++;
ch = input[i];
}
}
else
{
totalDenominator = 1;
}
return Rational(totalNumerator, totalDenominator);
}
If not, then it is some command or another. Just do a switch or something, and do the right thing with the stack. This makes it easy, and looking like a normal RPN calculator which you need to hit enter after each number for. My calculator looks at the first letter to determine which operator it is, for instance p is the same as print stack. You must implement the following operators:
> 5 > 4 > + 9 > 5 > / (9/5) > 3 > 2 > / (3/2) > p 0: (3/2) 1: (9/5) > + (33/10) > 2 > 10 > / (1/5) > + (7/2) > d 3.5 > 3 > 7 > / (3/7) > * (3/2) > n (-3/2) > c Stack Cleared >