算法测试自定义-函数指针【数据结构与算法笔记5】

注:依照计划,在MOOC上数据结构与算法的课python先行,C跟后。python的自定义算法测评倒是简单,C语言中则要使用函数指针做函数的参数。

函数指针简介:

参考一参考二,参考三:c++ primer plus第七章

例子:(未使用typedef)

#include <stdio.h>
#include <time.h>
#include <math.h>

clock_t start, stop;
double duration;
#define MAXN 10
double f1(int n, double a[], double x);
double f2(int n, double a[], double x);
void check(double (*p)(int n, double a[], double x),int q, double w[], double e);

int main()
{
	int i;
	double a[MAXN];
	for (i = 0; i < MAXN; i++) a[i] = (double)i;

	check(f1, MAXN - 1, a, 1.1);
	check(f2, MAXN - 1, a, 1.1);

	return 0;

}

void check(double (*p)(int n, double a[], double x), int q, double w[], double e)
{
	start = clock();
	(*p)(q, w, e);
	stop = clock();
	duration = ((double)(stop - start) / CLK_TCK);
	printf("tickls = %f\n", (double)(stop - start));
	printf("duration = %6.2e\n", duration);
}
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;
}

为何想这么搞呢 看下图
在这里插入图片描述
代码冗余严重

总结:

使用函数指针作为测评函数的参数, 然后在调用的时候将所要测试的代码(函数名)传入评测函数

发布了48 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/NewDreamstyle/article/details/102648068
今日推荐