由于本学期有一门计算方法的课需要C语言编程,在这里记录一下。
由于这是第一章且后面的课大约也有相似的属性,比如对n个点的使用和函数的调用,这里就进行一个小封装,方便以后吃老本。
欢迎需要参考的同学复制粘贴,互相交流.
//POINTS.h
#pragma once
#include
using namespace std;
#ifndef _POINTS_
#define _POINTS_
class POINTS
{
public:
typedef struct MYPOINT
{
double x;
double y;
}mypoint;
int len;
int size;
virtual void run(double val);
virtual void loaddata(double* vallist);
};
#endif // !_POINTS_
//POINTS.cpp
#include "POINTS.h"
#include
using namespace std;
void POINTS::run(double val)
{
cout << "计算函数" << endl;
}
void POINTS::loaddata(double* vallist)
{
cout << "数据处理函数" << endl;
}
//LAGRANGE.h
#pragma once
#include "POINTS.h"
#ifndef _LAGRANGE_
#define _LAGRANGE_
class LAGRANGE :
public POINTS
{
public:
LAGRANGE(int n);
vector datalist;
virtual void run(double val);
virtual void loaddata(double* vallist);
};
#endif // !LAGRANGE
//LAGRANGE.cpp
#include "LAGRANGE.h"
#include
using namespace std;
LAGRANGE::LAGRANGE(int n)
:datalist(n)
{
this->size = n;
this->len = 0;
}
void LAGRANGE::run(double val)
{
double sum = 0.0;
vector templist;
for (size_t i = 0; i < this->size; i++)
{
double tempval = 1.0;
for (size_t j = 0; j < this->size; j++)
{
if (j != i)
tempval *= ((val - this->datalist.at(j).x) /
(this->datalist.at(i).x - this->datalist.at(j).x));
else
continue;
}
templist.push_back(tempval);
}
for (size_t i = 0; i < this->size; i++)
{
sum += this->datalist.at(i).y * templist.at(i);
}
cout << "拉格朗日" << this->size << "项插值计算为:" << sum << endl;
}
void LAGRANGE::loaddata(double* vallist)
{
cout << "正在处理数据..." << endl;
for (size_t i = 0; i < this->size * 2; i++)
{
if (((i + 1) % 2) == 0)
{
this->datalist.at(this->len).y = vallist[i];
this->len++;
}
else
{
this->datalist.at(this->len).x = vallist[i];
}
}
}
//main.cpp
#include
#include"POINTS.h"
#include"LAGRANGE.h"
using namespace std;
int main()
{
cout << "例1" << endl;
//实例化工具类
LAGRANGE lgr(2);
//构建运算参数表
double val[4] = { 100.0,10.0,121.0,11.0 };
//调用处理数据函数
lgr.loaddata(val);
//传入目标x运算,例1
lgr.run(115);
//传入目标x运算,例2
cout << "例2" << endl;
LAGRANGE lgr1(3);
double val1[6] = { 100.0,10.0,121.0,11.0,144.0,12.0 };
lgr1.loaddata(val1);
lgr1.run(115);
//课上的题目求ln3.16
cout << "求ln3.16" << endl;
LAGRANGE lgr2(2);
double val2[4] = { 3.1,1.1314,3.2,1.1632 };
lgr2.loaddata(val2);
lgr2.run(3.16);
system("pause");
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)