作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在编写一个 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/
我是一名优秀的程序员,十分优秀!