Write your question here.
hey guys, I am supposed to write a program to work out x^n but I still don't understand C++, we were legit introduced to c++ 2 weeks ago and i'm very confused about how to start. we got given this, could anyone guide me in the direction or anything i can look at to help cause I can't seem to find exactly what i need and our lecturer is very vague in his notes.
Guess what, that's why they give you exercises to do.
Unless you take the sound advice of the previous two posts I hate to tell you, but you probably won't ever understand C++.
I would add though another piece of practical advice and why not consider how you would do it with a pencil and paper and write some pseudocode to map out your plan for coding.
Try it for the first of dhayden's cases as a start.
the reason why i complain about not understanding it is cause they are trying to pack a lot into one 10 credit module, and very quickly and the notes they provide are very brief
Your (n<0) case works, but, in the spirit of recursion, could alternatively be written
Zivvy's code for n<0 already uses recursion:
1 2
elseif (n<0)
return 1/power1(x,-n);
There's another reason to do it that way: performance. His was does n multiplications and 1 division. Yours does n divisions. Division typically takes longer than multiplication.
Thanks @dhayden: point taken. I was trying to avoid the problem of first having to calculate a potentially-large denominator as power1(x,-n) when x is large and n large and negative. However, perhaps I shoot myself in the foot, since mine could suffer from a similar problem when x is small.
@zivvy's code ran fine when I called his function; I'm bemused as to how it produces zero.