exponential function without using pow()

Hello!

I am trying to write a program that solves exponents without using the pow () function. I think I need to use a loop to generate how many times the base multiplies itself as long as the exponent is positive. Any ideas?



Thanks
One approach to this problem:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main()

{
    double n = 5; // We want 5^4
    int e = 4;
    double T = 1;

    for(int k=1; k<=e; k++)
	T = T*n;

    cout << T << endl;

    return 0;
}
Last edited on
cppmatt

Thanks for getting back to me! Your code works great, however if you don't mind, could you explain why you set T=1 & how T=T*n works?

Sorry I'm just getting started in programming and I just like to understand why it works rather than just watching it work.

thanks again
Well look at it like this. In the first iteration of the loop you have:
1
2
T(5^0)= T(5^0 or 1)*n(5)
T=5 or 5^1

second:
1
2
T(5)= T(5)*n(5)
T= 25 or 5^2

n-th:
1
2
T(5^(n-1))= T(5^(n-1))*n(5)
T= 5^n
Thanks so much, now for negative exponents, T = (1/(T*n)) <-- From the 1st post
right?
Two little modifications will help:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
int main()

{
    double n = 5; // We want 5^4
    int e = -4;
    double T = 1;

    for(int k=1; k<=abs(e); k++)
	T = T*n;
    T = (e<0) ? 1/T : T;

    cout << T << endl;

    return 0;
}
Last edited on
cppmatt & Mercurialol,

Thanks a lot! I really appreciate you two taking the time to explain this to a noobie. This is how I can hopefully get to your knowledge base some day!

Take care
I hope you will pass my current knowledge someday, as do I! I am only in the first month of my first c++ class myself...
Topic archived. No new replies allowed.