标签:递归 实现 计时 i++ span double tar 调用 star
1、写一个函数PrintN,使得传入一个N,打印从1到N的全部整数
#include<stdio.h> //循环实现 void PrintN(int N){ int i; for(i = 1;i<=N;i++){ printf("%d\n",i); } return; } //递归实现 void PrintN1(int N){ if(N){ PrintN1(N-1); printf("%d\n",N); } return; } int main(){ int N; scanf("%d",&N); PrintN(N); return 0; }
2、写程序计算给定多项式在给定点x处的值f(x)=a0+a1*x+...+an-1*x^(n-1)+an*x^n
将多项式写成如下形式:f(x)=a0+x(a1+x(...(an-1+x(an))...))
#include <stdio.h> #include <time.h> #include <math.h> clock_t start,stop; double duration; #define MAXN 10 /*多项式次数*/ #define MAXK 1e7 /*被测函数最大重复调用次数*/ double f1(int n,double a[],double x); double f2(int n,double a[],double x); int main(){ int i; double a[MAXN]; for (i=0;i<MAXN;i++) a[i]=(double)i; /*测试f1*/ start = clock(); /*开始计时*/ for(i=0;i<MAXK;i++) f1(MAXN-1,a,1.1); /*被测试函数*/ stop = clock(); /*停止计时*/ duration = ((double)(stop-start))/CLK_TCK/MAXK; printf("ticks1 = %f\n",(double)(stop-start)); printf("duration1 = %6.2e\n",duration); /*测试f2*/ start = clock(); for(i=0;i<MAXK;i++) f2(MAXN-1,a,1.1); stop = clock(); duration = ((double)(stop-start))/CLK_TCK/MAXK; printf("ticks2 = %f\n",(double)(stop-start)); printf("duration2 = %6.2e\n",duration); return 0; } double f1(int n,double a[],double x){ int i; double p = a[0]; for(i = 1;i<=n;i++) p+=(a[i]*pow(x,i)); return p; } double f2(int n,double a[],double x){ int i; double p = a[n]; for(i = 1;i>0;i--) p=a[i-1]+x*p; return p; }
结果:
标签:递归 实现 计时 i++ span double tar 调用 star
原文地址:https://www.cnblogs.com/cxc1357/p/10604797.html