# This should be fairly simple to fix.

Printable View

• 03-04-2004
Lancer
This should be fairly simple to fix.
Okay, will somebody tell me what is wrong with this code?

Code:

```#include <iostream.h> typedef unsigned short int USHORT; typedef unsigned long int ULONG; ULONG powerFunc(USHORT, USHORT, USHORT); int main() {   USHORT num, orignum, pow; ULONG ans;   cout<<"Enter a number and a power:\t"; cin>>num;   cout<<"\t\t\t\t"; cin>>pow;   orignum=num;   ans=powerFunc(num, orignum, pow);   cout<<"\n\n"<<num<<" to the power of "<<pow<<" equals "<<ans<<".\n\n";   return 0; } ULONG powerFunc(USHORT num, USHORT orignum, USHORT pow) {   cout<<"num="<<num<<" orignum="<<orignum<<" pow="<<pow<<"\n\n";   if (pow!=1)   {     num=num*orignum;     pow--;     powerFunc(num, orignum, pow);   }   cout<<"num to return="<<num;   return num; }```
Here is the output I get:
Code:

```Enter a number and a power:    2                                 4 num=2 orignum=2 pow=4 num=4 orignum=2 pow=3 num=8 orignum=2 pow=2 num=16 orignum=2 pow=1 num to return=16num to return=16num to return=8num to return=4 2 to the power of 4 equals 4.```

I've been messing with it for about an hour with no results. I am guessing it has something to do with local variables.
• 03-04-2004
gautamn
Hi,

I think your powerfunc is totally wrong. I suppose you want to do some 2^4 = 2 * 2 * 2 * 2.

So you should be doing

Code:

```ULONG powerFunc(USHORT num, USHORT pow) {     if (pow < 1) return 1;     else return num * powerFunc(num, --pow); }```
Edit : By the way in your original code num will always be 2 and orignum will always be 2 so num = num *orignum will always be 2 * 2 = 4.
• 03-04-2004
Lancer
Thanks a lot, that works perfectly.
• 03-04-2004
major_small
nitpicking:
Code:

`#include<iostream.h>`
should be
Code:

```#include<iostream> using namespace std;```
it's more standards-compliant...