Program for x^y with negative powers

#include <iostream>
#include <cstdlib>
using namespace std;

float power(float,int);

int main()
{
float base;
int exponent;
float result;
cout<<"Enter base : ";
cin>>base;
cout<<"Enter power : ";
cin>>exponent;
result=power(base,exponent);
cout<<base<<" ^ "<<exponent<<" = "<<result;
cout<<"\n";
return 0;
}

float power(float base, int exponent)
{
int p;
p=abs(exponent);
float result;
result=base;
for (int i = 1; i < exponent; ++i)
{
result=result*base;
}

float reciprocal;
reciprocal=1/result;

if (exponent>0)
return result;
else
if(exponent<0)
return reciprocal;
else
return 1;
}

I am not sure whats wrong with the program but its giving 10^-3 as 0.1
for (int i = 1; i < p; ++i)
Your problem is that you never use the p value, but instead you use the exponent which may be negative in your loop, so instead of iterating it will stop as 1 will be greater than any negative value

Here's how it should be:

1
2
3
for (int i = 1; i < abs(exponent); ++i)
  result*=base;
Last edited on
Topic archived. No new replies allowed.