Representing a power

Can someone tell me how I'm meant to represent a power in a function? Obviously I can't use ^. For example, in an interest calculation such as:
Interest = Base * (1 + Rate)^Years - Base,
you can't know what the Years value will be so you can't use a simple set of *s either.
Well obviously I should have found that myself, but in any case I don't understand what it means. If I follow the example there it asks me to specify the kind of pow I want. That just starts bringing up more errors. I know this:
interest = base * (double std::pow (1 + rate), years) - base;
is wrong, but why? What syntax would I use for this?
interest = base * pow (1 + rate, years) - base;

Last edited on
Oh of course, I'm defining it as I use it. This is why I'm in the beginners forum.
And of course now I'm getting this value: 4.24399e-314.
I should be getting: 4105.98760621122182512197265625.
Here's the code, it's just a driver but I've still managed to get it wrong. The only idea I had was using long doubles but that doesn't help and anyway the exercise I'm working from specifies doubles.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cmath>
using namespace std;

double getInterest (double base, double rate, int years)
{
       
       double interest;
       
       interest = base * pow (1 + rate, years) - base;
       
}
 int main ()
 {
     double interest;
     double base = 10000;
     double rate = 0.035;
     int years =10;
     cout << "The total interest is: " << interest << endl;
     cin.get ();
     cin.get ();
 }
Last edited on
Hmmm... Your interest variable in main and your interest variable in your getInterest function are two different things. Somewhere in your main, and before printing, you should call getInterest like this:

interest=getInterest(base, rate, years);

Oh, and in your getInterest function don't forget to add a return interest; statement at the end.

I gather that you are rather new with functions. These links here could help:

http://cplusplus.com/doc/tutorial/functions/
http://cplusplus.com/doc/tutorial/functions2/
Right... I think I made some strange assumption that including the function in the same program would automatically call it. Are beginners often this strange or is it just me? In any case it all works fine now, even if I change the figures. And even better, I understand why it works.

I don't suppose you can help out with my other current problem?:
http://www.cplusplus.com/forum/beginner/28027/
I seem to work well with your instructions.
Last edited on
Are beginners often this strange or is it just me?


Happens all the time, don't worry about it.
Topic archived. No new replies allowed.