Edit: Sorry I am using Visual C++ 2019 |
Why would you be "sorry" for using the latest software?
I'm tempted to post you a full code but instead here are just pieces and building blocks:
I recommend you to verify these functions and constructs here:
https://en.wikipedia.org/wiki/Exponentiation
If you want your power function to be universal, that is to handle any valid input declare a template like this:
1 2
|
template<typename B, typename E>
double pow(B base, E exponent)
|
Next first thing you want to check is invalid input:
1 2 3 4
|
// 0^-n = UNDEFINED
// 0^0 = UNDEFINED
if (base == 0 && exponent <= 0)
// handle error
|
another invalid input case:
1 2 3 4 5
|
if(std::is_floating_point<B>::value && std::is_floating_point<E>::value && base < 0 && exponent < 0)
{
// would be valid for complex numbers only!
throw 0;
}
|
then also, there are inputs for which calculation is very simple, do this next!
1 2 3 4 5 6 7 8
|
if (base == 0)
return 0; // b^0 = 0 [where b not 0]
if (base == 1 || exponent == 0)
return 1;
if (exponent == 1)
return base; // b^1 = b
|
OK, now that you know user input is valid, only at this point you do the calculation, I'll give just the formula, you part of the job is to figure out how to implement it in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
// First check if exponent is integral value!
if (std::is_integral<E>::value)
{
if (exponent < 0)
{
// b^-n = 1/(b^-(-n))
}
else
{
// b^n = b * b^(n-1)
}
}
// if exponent is not integral calculation is more complicated!
else if (exponent >= 1)
{
// positive decimal exponent grater than 1
// (b^(x/y) = y-th root of b^x) OR (b^(1/n) = n-th root of b) [where b > 0]
}
else
{
// decimal exponent positive less then 1 or negative
// (b^(x/y) = exp((x/y) * ln(b))) OR (b^n = exp(n ln(b))) [where b > 0 | n = R]
}
|
EDIT:
this code can be further improved, such as handling the epsilon if exponent is not integral.
but we'll get to that point once you implement the above code.
Let me know if you need help or hints!