Writing a program to find x^n

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;

/* compute x^n using recursion */
double power1(const double x, const int n) {
    //....
   
    
    

    
}

/* compute x^n using recursion */
double power2(const double x, const int n) {
    //....
    
    
}
The recursive function has 3 cases that you should deal with:
n==0 : answer is 1;
n<0 : answer is 1.0 / x-n
n > 0 : answer is x * xn-1
closed account (48T7M4Gy)
I still don't understand C++

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
thanks for the advice
double power1(const double x, const int n) {
// Do it!

if (n==0)
return 1;
else if (n<0)
return 1/power1(x,-n);
else
return x*power1(x,n-1);
}


i wrote this and it compiles but when i run it and enter any numbers it just returns 0
Can you show your whole code (including main() and headers). Preferably between code tags. With suitable function call, your code works OK.

Your (n<0) case works, but, in the spirit of recursion, could alternatively be written
1
2
else if (n<0)
return power1(x,n+1) / x;
Last edited on
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
else if (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.
Last edited on
closed account (48T7M4Gy)
0 to the power 0 is the fourth one?
Topic archived. No new replies allowed.