Good Afternoon, I am trying to create a power(base, exponent) that can interpret positive exponents, negative exponents and zero. I have the program working for positive exponents and exponents that are 0, but when I try to enter a negative exponent. Codeblocks lets me, but the terminal tells me:
Segmentation fault (core dumped)
What must I fix? I have tried googling and searching forums, but the topics that I see look pretty much the same to me as my own function.
Thank you for your time.
Segmentation fault (core dumped)
What must I fix? I have tried googling and searching forums, but the topics that I see look pretty much the same to me as my own function.
#include <iostream>
using namespace std;
float power (float base, float exponent)
{
if ( 0 == exponent)
{
return 1;
}
else if ( 1 != exponent)
{
base *= power(base, exponent - 1); // don't forget power in power(base, exponent)
}
else if ( exponent < 0 )
{
return 1 / power(base, -exponent);
}
return base;
}
int main ()
{
cout<<"Enter your base: ";
float base;
cin>>base;
cout<<"Enter your exponent: ";
float exponent;
cin>>exponent;
cout<<"The answer is "<<power(base, exponent);
}
Thank you for your time.