1. Description of the problem
Implementation functions:
Double power (double base,int exponent)
To find the exponent of base, do not use the library function, do not consider the problem of large numbers.
2. Solution 1
consider boundary issues;
#include <iostream> #include <string> using namespace std; #define Dbl_min 0.000001 Double power (double base, int exponent) {if (Base < Dbl_min && Base >-dbl_m
In) {return 0.0;
Double result = 1.0;
int unsignedexponent = exponent;
if (Exponent < 0) {unsignedexponent =-exponent;
for (int i = 1; i < unsignedexponent. i++) {result *= base;
} if (Exponent < 0) {result = 1.0/result;
return result;
int main (int argc, const char * argv[]) {double base = 12.0;
int exponent =-2; cout<< "base = <<base<<"; exponent = "<<exponent<<";
The result is: "<<power (base, exponent) <<endl;
base = 0.0;
exponent = 2; cout<< "base = <<base<<"; exponent = "<<exponent<<";
The result is: "<<power (base, exponent) <<endl;
base =-0.000000009;
exponent = 12; cout<< "base = <<base<<"; exponent = "<<exponent<<";
The result is: "<<power (base, exponent) <<endl;
return 0; }
2. Solution 2
Assuming that the solution 32 times, if the known 16 times, then as long as 16 square on the basis of the second time can be, and 16 square is 8 square squared, an analogy.
#include <iostream> #include <string> using namespace std; #define Dbl_min 0.000001 Double powerunsignedexponent (double base, int exponent) {if (exponent = 0) {R
Eturn 1.0;
} if (exponent = = 1) {return base;
}//exponent >> 1 = exponent/2 double result = Powerunsignedexponent (base, exponent>>1);
Result *= result;
If exponent is odd if (exponent & 0x01) = = 1) {result *= base;
return result; Double power (double base, int exponent) {if (Base < Dbl_min && Base >-dbl_min) {retur
n 0.0;
Double result = 1.0;
int unsignedexponent = exponent;
if (Exponent < 0) {unsignedexponent =-exponent;
result = Powerunsignedexponent (base, unsignedexponent);
if (Exponent < 0) {result = 1.0/result;
return result; int main (int arGC, const char * argv[]) {double base = 12.0;
int exponent =-2; cout<< "base = <<base<<"; exponent = "<<exponent<<";
The result is: "<<power (base, exponent) <<endl;
base = 0.0;
exponent = 2; cout<< "base = <<base<<"; exponent = "<<exponent<<";
The result is: "<<power (base, exponent) <<endl;
base =-0.000000009;
exponent = 12; cout<< "base = <<base<<"; exponent = "<<exponent<<";
The result is: "<<power (base, exponent) <<endl;
return 0;
}
reference:"sword refers to the name of an offer to be interviewed by a typical program"-Face question 11: The integer number of the value of the second party