1题目
2分析
3代码
#include <iostream>
#include <ctime>
#include <cmath>
using namespace std;
clock_t start, stop;
const int MAXK = 1e5;
double duration;
double f1(double x);
double f2(double x);
void printFunTime(double (*p)(double x));
int main()
{
printFunTime(f1);
printFunTime(f2);
system("pause");
return 0;
}
void printFunTime(double (*p)(double x))
{
double ret;
start = clock(); //开始计时
for (int i = 1; i < MAXK; i++)
ret = p(1.1);
stop = clock();
duration = ((double)(stop - start)) / CLK_TCK / MAXK;
cout << duration << " " << ret << endl; //输出时间和结果
}
double f1(double x) //逐项求解
{
double sum = 1.0;
int i;
for (i = 1; i <= 100; i++)
sum += pow(x, i) / i;
return sum;
}
double f2(double x) //合并
{
double p = 1.0 / 100;
int i;
for (i = 99; i >= 1; i--)
p = 1.0 / i + x * p;
p = 1 + p * x;
return p;
}
4运行结果