C语言多项式加法mooc答案,【参考答案】1.3 再试一个多项式 - C语言版

置顶

老师参与

【参考答案】1.3 再试一个多项式 - C语言版

陈越

发表于2020年10月09日

#include <stdio.h>

#include <time.h>

#include <math.h>

clock_t start, stop;

double duration;

#define MAXN 101 /* 多项式最大项数,即多项式阶数+1 */

#define MAXK 1e5 /* 被测函数最大重复调用次数*/

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=n; i>0; i-- )

p = a[i-1] + x*p;

return p;

}

void run( double (*f)( int, double*, double ), double a[], int case_n )

{/* 此函数用于测试被测函数(*f)的运行时间,并且根据case_n输出相应的结果 */

 /* case_n是输出的函数编号:1代表函数f1;2代表函数f2                   */

int i;

double p;

start = clock();

for ( i=0; i<MAXK; i++ ) /* 重复调用函数以获得充分多的时钟打点数*/

p = (*f)(MAXN-1, a, 1.1);

stop = clock();

printf("p%d = %f\n", case_n, p);

duration = ((double)(stop - start))/CLK_TCK;

printf("ticks%d = %f\n", case_n, (double)(stop - start));

printf("duration%d = %6.2e\n", case_n, duration);

}

int main ()

{

int i;

double a[MAXN]; /* 存储多项式的系数*/

/* 为本题的多项式系数赋值 */

a[0] = 1.0;

for ( i=1; i<MAXN; i++ ) a[i] = 1.0/(double)i;

run(f1, a, 1);

run(f2, a, 2);

return 0;

}

分享

0

回复

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值