Answer the question
In order to leave comments, you need to log in
Recursion. Why is the answer always 0?
Describe a recursive function PowerN(X, N) of real type that finds the value of the Nth power of the number X using the formulas:
X 0 = 1,
XN = (XN / 2)2 for even N > 0,
XN = X XN–1 for odd N > 0,
XN = 1/X –N for N < 0
(X ≠ 0 is a real number, N is an integer; integer division must be used in the formula for even N). With this function, find the XN values for a given X given five N values.
My code is:
#include <iostream>
#include <cmath>
using namespace std;
float power(float X, int N){
if (N != 0){
if (N < 0){
return 1 / power(X, -N);
}
else if(N>0){
if (N % 2 == 0){
float b=power(X, N/2);
return pow(b,2);
}
else{
return X * power(X, N - 1);
}
}
else{
return 1;
}
}
}
int main(){
float X;
int N;
cout<<"X=";
cin>>X;
for (int i=0;i<=5;i++){
cout<<"N=";
cin>>N;
cout<<X<<"^"<<N<<"="<<power(X,N)<<endl;
}
}
Answer the question
In order to leave comments, you need to log in
Carefully place indents. You have the if else logic messed up there, and the program does not at all what you would like. Also, look carefully at the warnings from the compiler (it will definitely say that power sometimes does not return any values, although it seems to you that return is in all branches of if else). This is just because your parentheses are not so spaced and the else does not belong to the if at all, as you would like.
Learn to write beautifully. Instead of nesting nested if/else , use an early exit from the function.
float power(float X, int N) {
if (N == 0) {
return 1;
}
if (N < 0) {
return 1. / power(X, -N);
}
if (N % 2 == 0) {
float b = power(X, N / 2);
return b * b;
}
return X * power(X, N - 1);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question