数据结构学习1

数据结构学习1

//计算多项式在给定x处的值
#include<iostream>
#include<algorithm>
#include<cmath>
#include<ctime>
using namespace std;
clock_t start,stop;  //clock_t是clock()函数返回的变量类型
double duration;   //记录函数运行时间
#define MAXK 1e7
//直接法
double f1(int n,double a[],double x)
{
	double res = 0;
	for(int i=0;i<n;i++)
	{
		res+=(a[i]*pow(x,i));
	}
	return res;
}
//仿秦九绍算法
//f0 = a0+x(a1+x())
double f2(int n,double a[],double x)
{
	double ans = a[n];
	for(int i=n;i>0;i--)
	{
		ans=a[i-1]+x*ans; 
	}
	return ans;
}
int main()
{
	cout<<"请输入x"<<endl;
	double x;
	cin>>x;
	double a[]={1,2,3};
	int n = 3;
	start = clock();
	for(double i=0;i<MAXK;i++)
	{
//		f1(n,a,x);
		f2(n,a,x);
	}
//	double res = f1(n,a,x);
//	double ans = f2(n,a,x);
	stop = clock();
	duration = ((double)(stop-start))/CLK_TCK;
//	cout<<res<<endl;
//	cout<<ans<<endl;
	cout<<"运行时间"<<duration<<endl;
	return 0;
}
/*
计算程序的时间效率,可以调用一个clock() :捕捉程序从开始 运行到 clock() 被调用所耗费的时间
单位clock tick 时钟打点
*/
//duration = 0 因为程序执行过快 

0.15 0.091

原文地址:https://www.cnblogs.com/serendipity-my/p/13779700.html