#include<stdio.h>
#include<time.h>
#include<math.h>
#define MAXREPEAT 1e7
#define MAXN 101
typedef double(*func)(int, double );
void timeCost (func myFunc , int n , double x);
double func1(int n , double x);
double func2(int n , double x);
int main(int argc , const char *argv[]){
int n =MAXN;
double x = 1.1;
printf("fun1结果为:%lf\n", func1(n,x));
timeCost(func1 , n, x);
printf("func2结果为:%lf\n",func2(n,x));
timeCost(func2, n ,x);
return 0;
}
void timeCost (func myFunc , int n , double x)
{
clock_t start , stop;
double duration;
start = clock();
int i;
for( i = 0; i < MAXREPEAT ; i++){
myFunc(n,x);
}
stop = clock ();
duration = ((double)(stop-start))/CLOCKS_PER_SEC;
printf("用时%f秒\n",duration);
}
double func1(int n, double x)
{
double p =1;
int i;
for( i =1 ;i<n;i++){
p += pow(x,i)/i;
}
return p;
}
double func2(int n ,double x)
{
double p =1.0/(n-1);
int i =0;
for(i = n-1 ;i> 0 ; i--)
{
if(i ==1){
p = 1+x*p;
}else{
p =1.0/(i-1) + x*p;
}
}
return p;
}原文:http://9815936.blog.51cto.com/9805936/1637259