gpt4 book ai didi

C++ 程序已停止工作 - 求解常微分方程

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:14:08 25 4
gpt4 key购买 nike

我正在编写一个 C++ 程序来为大学作业寻找一阶微分方程的解。程序启动,然后一旦我输入要执行的迭代次数,我就会收到错误消息“Euler 的 method.exe 已停止工作”。这是我的代码:

#include <functional>
#include <vector>

using namespace std;


double f_r(double x, double r) {
return r;
}

double f_s(double x, double s) {
return -x/s;
}


double eulerstep(const function<double(double,double)>& f, double xsub0, double ysub0, double h) {
double ysub1 = ysub0+ h * f(xsub0,ysub0);
return ysub1;
}


double euler(const function<double(double,double)>& f, double xsub0, double ysub0, double h, int n) {
vector<double> xsub;
vector<double> ysub;
xsub[0] = xsub0;
ysub[0] = ysub0;
n = ysub.size();
for (int i=1; i<n; i++){
xsub[i+1] = xsub[i] + h;
ysub[i+1] = ysub[i] + h * f(xsub[i],ysub[i]);
cout << xsub[i] << " , " << ysub[i] << endl;
}
return ysub[n];
}

int main() {
int nsteps = 0;
cout << "Number of steps?" << endl;
cin >> nsteps;
double h = 1.0 / nsteps;

double r = euler(f_r,0,1,h,nsteps);


double s = euler(f_s,0,1,h,nsteps);

return 0;
}

我相当确定问题在于我如何定义我的 vector ,但我是使用它们的新手,所以看不出我哪里出错了。如果有人能指出我方法中的错误,我将不胜感激

谢谢

最佳答案

这是一个更新的函数。您必须设置大小,而不是向空 vector 询问其大小。

double euler(const function<double(double, double)>& f, double xsub0, double ysub0, double h, int n)
{
vector<double> xsub;
vector<double> ysub;
xsub.resize(n+1); // so we can access [n], it must be size n+1
ysub.resize(n+1);
xsub[0] = xsub0;
ysub[0] = ysub0;
for (int i = 1; i<n; i++) {
xsub[i + 1] = xsub[i] + h;
ysub[i + 1] = ysub[i] + h * f(xsub[i], ysub[i]);
cout << xsub[i] << " , " << ysub[i] << endl;
}
return ysub[n];
}

关于C++ 程序已停止工作 - 求解常微分方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36191605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com