11.1—分治法—Pow(x,n)

来源:互联网 发布:linux下的下载工具 编辑:程序博客网 时间:2024/05/28 05:18
描述
Implement pow(x, n).

#include<iostream>#include<cmath>using namespace std;#define eps 0.0000001bool flag = true;double MyPow(double x, int n){if (n == 0){if (abs(x) >= eps)return 1;else{cerr << "0的0次方无意义!" << endl;flag = false;return -1;}}else if (n > 0){if (abs(x) < eps){return 0;}else{if (n % 2 == 0){double temp=MyPow(x, n / 2);return temp*temp;}else{double temp = MyPow(x, (n-1) / 2);return x*temp*temp;}}}else{if (abs(x) >= eps)return 1.0 / MyPow(x, -n);else{cerr << "0的" << n << "次方无意义!" << endl;flag = false;return -1;}}}int main(){int n = 5;double x = 4;double res = MyPow(x, n);if (flag)cout << res << endl;}