3 Replies - 3796 Views - Last Post: 29 October 2009 - 06:25 PM Rate Topic: -----

#1 jj123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 08-October 09

calculate base and exponent and return result.

Post icon  Posted 29 October 2009 - 04:40 PM

Somebody please help me. I have to calculate the base to any exponent using my own function and not the default. The function name is power and I have to return the value. There isn't any errors when i run it it asks for the base and asks for the exponent but it doesn't give me the correct answer. EX: I put 2 to the 3th power and the result should be 8 but it gives me 35424852.

#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>

int power(int base, int exponent);
int power(int base, int exponent)
{
	 int intpower = base;
	 int i;

	 if (exponent <1){
						return 1;
			}
	 for ( i = 1; i <= exponent; ++i ) {
					   
						intpower = base;
	   }

	   return intpower * (power(base,exponent-1));
}

int printf(int base, int exponent);
int printf(int base, int exponent)
{
   int intpower;
   cout<<"Enter the Base: ";
   cin>>base;
   cout<<"Enter the Exponent: ";
   cin>>exponent;
   cout<<"The result is: "<<intpower<<endl;
}

int main()
{
	 int base, exponent;
	 power(base, exponent);
	 printf(base, exponent);
	 system("PAUSE");
	 return 0;
}


Is This A Good Question/Topic? 0
  • +

Replies To: calculate base and exponent and return result.

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6039
  • View blog
  • Posts: 23,436
  • Joined: 23-August 08

Re: calculate base and exponent and return result.

Posted 29 October 2009 - 05:01 PM

Shouldn't you set base and exponent to something before you call your function?

What's the value of intpower going to be here?
int printf(int base, int exponent)
{
   int intpower;
   cout<<"Enter the Base: ";
   cin>>base;
   cout<<"Enter the Exponent: ";
   cin>>exponent;
   cout<<"The result is: "<<intpower<<endl;
}


Was This Post Helpful? 0
  • +
  • -

#3 zhanfeng  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 75
  • Joined: 09-November 08

Re: calculate base and exponent and return result.

Posted 29 October 2009 - 05:04 PM

The while loop in the power function is useless. You can just take that out.
Was This Post Helpful? 0
  • +
  • -

#4 GenHornet18  Icon User is offline

  • Darken the Radar

Reputation: 36
  • View blog
  • Posts: 629
  • Joined: 19-October 09

Re: calculate base and exponent and return result.

Posted 29 October 2009 - 06:25 PM

while yes some of your code is useless, the main point here is your need

#include<cmath>
	 // 2^3
	 int answer = pow(2,3);


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1