Will these methods properly work with the pre-allocated fractions? I have these working within a method which will break a fraction into a top and bottom string which is then dealt with through these functions. I just want to know if this is correct. Thank you.
string addFrac(string top, string bot, double d1)
{
int t = stoi(top);
int b = stoi(bot);
int numAdd = static_cast<int>(d1) * b;
t = t + numAdd;
return (t + "/" + b);
}
string subFrac(string top, string bot, double d1)
{
int t = stoi(top);
int b = stoi(bot);
int numSub = static_cast<int>(d1) * b;
t = t - numSub;
return (t + "/" + b);
}
string multFrac(string top, string bot, double d1)
{
int t = stoi(top);
int b = stoi(bot);
int numMult = static_cast<int>(d1) * t;
t = numMult;
return (t + "/" + b);
}
string divFrac(string top, string bot, double d1)
{
int t = stoi(top);
int b = stoi(bot);
int numDiv = t / static_cast<int>(d1);
t = numDiv;
return (t + "/" + b);
}
string pwrFrac(string top, string bot, double d1)
{
int t = stoi(top);
int b = stoi(bot);
int numPwr = pow(t, static_cast<int>(d1));
int denomPwr = pow(b, static_cast<int>(d1));
return (numPwr + "/" + denomPwr);
}
Have you tried using a debugger? If you are using an IDE there should be an easy to use GUI debugger somewhere. One can have a watch list of variables, monitor how their values change as you step through the code 1 line at a time - thus deduce where things go wrong. This will save you days of staring at code.
If not using an IDE, there are command line versions - which are a little trickier to learn - but not impossible. There are Articles on this site on how to use gdb.
Just a couple of very minor things about your code:
STL container functions size() usually return a type of size_type which is often typedef'd to std::size_t
I was just thinking for example on line 92 you could have this to avoid the c style cast:
size_type StackSize = st.size();
or if that doesn't work use std::size_t :
std::size_t StackSize = st.size();
In general, avoid using c style casts - use static_cast</*type*/>(/*variable*/) instead.
Line 82 is a bit of a worry problem:
result is a double, so constructs like this are a concern always will be true:
result != (signedint)result)
which means your string is never pushed onto the stack. There are a number of instances of these in your code.
As well as that, this line 82 is not scalable - what if you had 20 or 50 operators? A better option would be to use switch or ifelse chain.
A final thing, IMO you have too much code in this function. A function should do one logical thing, at the moment you have several things going on - process stack, do calcs, output etc.
Hope this has helped :+) If I have possibly solved your problem, I still think it would be well worth your time to verify what I have said using a debugger.