The function has the following functionality:
exp(x, y) =
| 0, x = 0,
| 1, \forall x \notequal 0 and y = 0.
| xy, otherwise
As a result of the above, write a corresponding recursive C++ function, exp(x, y), computing the exponentiation function with the given specifications.
#include <iostream>
using namespace std;
double exp(double x, int y) {
if (y < 0) {
return exp(x, -y);
}
if (x == 0) {
return 0;
}
if (y == 0) {
return 1.0;
}
return exp(x, y-1) * x;
}
int main() {
double x;
int y;
cout << "Enter x: ";
cin >> x;
cout << "Enter y: ";
cin >> y;
cout << "exp(" << x << ", " << y << ") = " << exp(x, y);
return 0;
}
Comments
Leave a comment