`#include
using namespace std;
double func(double x, double y)//自定义函数
{
if (x == 0)
return 1;
return y - (2 * x) / y;
}
void 龙格库塔(double a,double b,int n) //a~b范围内的函数求值,n为求值的次数;
{
//初始化
double K[4] = { 0.0,0.0,0.0,0.0 };
double h = (b - a) / n;//步长
double p = h / 2.0;
double x = a;
double y[2] = { 0.0,0.0 };
y[0] = func(x, y[0]);
//核心
while (true) {
K[0] = func(x, y[0]);
x = x + p;
K[1] = func(x, y[0] + (h / 2.0) * K[0]);
K[2] = func(x, y[0] + (h / 2.0) * K[1]);
x = x + p;
cout << "x:" << x << endl;
if (x > b + 0.0000001)
break;
K[3] = func(x, y[0] + h * K[2]);
y[1] = y[0] + (h / 6.0) * (K[0] + 2.0 * K[1] + 2.0 * K[2] + K[3]);
cout << y[1] << endl;
y[0] = y[1];
}
}
int main() {
龙格库塔(0.0, 1.0, 10);
}`
上述运行结果为:

浙公网安备 33010602011771号