Need help with defining a function!
Oct 17, 2013 at 4:53am UTC
For this assignment we are supposed to define a function that finds the answer to x^n. I have it to where it will solve for both positive and negative exponents, but when zero is an input, the output is "nan." Any ideas of how to solve this problem? I was told to use an if statement somewhere, but I'm not sure where or how. Any help/advice would be greatly appreciated!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <iostream>
using namespace std;
double power(double base, int exponent);
int main() {
double x;
int n;
cin >> x;
cin >> n;
cout << power(x, n) << "\n" ;
return 0;
}
double power(double base, int exponent){
double x;
int n;
double product;
n = exponent;
x = base;
product = 1;
while (n >= 0){
product = x * product;
n = n - 1;
}
while ((-n) > 0){
product = 1/x * product;
n = 1 - (-n);
}
return product;
}
Oct 17, 2013 at 7:12am UTC
Try this slight modified:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include <iostream>
using namespace std;
double power(double base, int exponent);
int main() {
double x;
int n;
cout << "Enter x: " ;
cin >> x;
if (x == 0)
{
cout << "Enter a nonzero value for x !" ;
return 0;
}
cout << "Enter n: " ;
cin >> n;
double pow;
if (n == 0)
pow = 1.0;
else
pow = power(x, n);
cout << pow << "\n" ;
return 0;
}
double power(double base, int exponent){
double x;
int n;
double product;
n = exponent;
x = base;
product = 1;
while (n >= 0){
product = x * product;
n = n - 1;
}
while ((-n) > 0){
product = 1/x * product;
n = 1 - (-n);
}
return product;
}
Last edited on Oct 17, 2013 at 7:21am UTC
Topic archived. No new replies allowed.