hello,I am trying to build a power function that works like <cmath> pow();
and also is done with recursion.
2 power n works as long as n is a real number.
what i cant get to work is when is has decimal places.
now the way i tried to solve this problem,is to first find the number of decimal places in n.Then calculate 10 to the power of the decimal places in n(lets call this x).Then multiply n with the previous number(giving us a number without decimals),and finally calculate power(number we want to power,number without decimals),and after that calculate the X root of that number,giving us the final answer.
however i cant get this to work.here is my code,i think its a logical,problem,most likely with the recursion,because this method should work.
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 45 46 47 48 49 50 51 52 53 54
|
double Power (double a,double b);
double nthRoot(double num, double n_){//calculate nth root of n
//this code isn't necessary
}
//----------------------
double Power (double a,double b){
bool isNegative=false;
bool isDecimal=false;
double root;
double c;
//-------------------
if(((b-floor(b))!=0.0)){//check if b has decimal places(this is one of the things i dont thing they work)
isDecimal=true;
std::ostringstream strs;
strs << (b-floor(b));
std::string DoubleString = strs.str();
int DecimalPlaces =(DoubleString.length()-2);
double root=Power(10,DecimalPlaces);
b=b*root;
}
//---------------------
if(b==0){
return 1;
}else{
c=a*Power(a,abs(b)-1);
}
//--------------------
if(isDecimal==true){
c=nthRoot(c,root);
}
if(isNegative==true) {
return 1/c;
}else{
return c;
}
}
|