C语言中函数名可以做参数(通过传递函数地址的方式)格式如下(设被引用函数名为add,要引用此函数的函数名为test``)
函数定义
//引用函数返回值类型 引用函数名(被引用函数返回值类型 被引用函数名(参数一类型,参数二类型...),参数一类型 参数一值,..)
void test(long (*add)(long),long n)
{
clock_t t;
long sum;
t=clock();
sum=add(n);
t=clock()-t;
printf("数值:%ld\n",sum);
printf("时间:%lf\n",((float)t)/CLOCKS_PER_SEC);
}
函数引用`
test(add1,n);
完整代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
//求1~n连续整数和,n要大于100000,比较两种方法用时区别
//方法一
long add1(long n)
{
long m=0;
for(long i=1;i<=n;i++)
{
m+=i;
}
return m;
}
//方法二
long add2(long n)
{
return((1+n)/2*n);
}
//计时函数
void test(long (*add)(long),long n)
{
clock_t t;
long sum;
t=clock();
sum=add(n);
t=clock()-t;
printf("数值:%ld\n",sum);
printf("时间:%lf\n",((float)t)/CLOCKS_PER_SEC);
}
int main()
{
int n;
printf("请输入数值(大于1000000):");
scanf("%d",&n);
printf("方法一结果为\n");
//方法一下的计时结果
test(add1,n);
//方法二下的计时结果
printf("方法二结果为\n");
test(add2,n);
return 0;
}