用c++写一个画样条函数的程序
时间: 2023-06-17 22:05:12 浏览: 84
以下是C++代码,实现了样条曲线的绘制:
```c++
#include <iostream>
#include <graphics.h>
using namespace std;
const int MAX_N = 1005;
int n;
double x[MAX_N], y[MAX_N];
double a[MAX_N], b[MAX_N], c[MAX_N], d[MAX_N];
void cubicSpline() {
double h[MAX_N], alpha[MAX_N], l[MAX_N], mu[MAX_N], z[MAX_N];
for (int i = 1; i < n; i++) {
h[i] = x[i + 1] - x[i];
alpha[i] = 3.0 * (a[i + 1] - a[i]) / h[i] - 3.0 * (a[i] - a[i - 1]) / h[i - 1];
l[i] = 2.0 * (x[i + 1] - x[i - 1]) - h[i - 1] * mu[i - 1];
mu[i] = h[i] / l[i];
z[i] = (alpha[i] - h[i - 1] * z[i - 1]) / l[i];
}
for (int i = n - 1; i >= 1; i--) {
c[i] = z[i] - mu[i] * c[i + 1];
b[i] = (a[i + 1] - a[i]) / h[i] - h[i] * (c[i + 1] + 2.0 * c[i]) / 3.0;
d[i] = (c[i + 1] - c[i]) / (3.0 * h[i]);
}
}
double f(double t, int i) {
double ti = x[i];
double ti1 = x[i + 1];
double hi = ti1 - ti;
double a0 = y[i];
double a1 = (y[i + 1] - y[i]) / hi - hi * (a[i + 1] + 2.0 * a[i]) / 3.0 - hi * (c[i + 1] - c[i]) / 3.0;
double a2 = c[i] / 2.0;
double a3 = (c[i + 1] - c[i]) / (6.0 * hi);
return a0 + a1 * (t - ti) + a2 * (t - ti) * (t - ti) + a3 * (t - ti) * (t - ti) * (t - ti);
}
int main() {
cout << "请输入点的数量:";
cin >> n;
cout << "请按照 x y 的格式,输入点的坐标:" << endl;
for (int i = 1; i <= n; i++) {
cin >> x[i] >> y[i];
}
a[1] = a[n] = 0;
for (int i = 2; i < n; i++) {
double hi = x[i] - x[i - 1];
double hi1 = x[i + 1] - x[i];
double yi = y[i] - y[i - 1];
double yi1 = y[i + 1] - y[i];
a[i] = 3.0 * (hi * yi1 + hi1 * yi) / (hi + hi1);
}
cubicSpline();
initgraph(640, 480);
for (double t = x[1]; t <= x[n]; t += 0.01) {
for (int i = 1; i < n; i++) {
if (t >= x[i] && t <= x[i + 1]) {
double p = f(t, i);
double q = f(t + 0.01, i);
line((int)t, (int)p, (int)(t + 0.01), (int)q);
break;
}
}
}
getch();
closegraph();
return 0;
}
```
注意,这个程序需要在 Windows 系统下使用 graphics.h 库进行绘图,如果你使用的是其他操作系统,可以使用其他绘图库,如 OpenGL。
阅读全文