我有一个C++程序:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cmath>
using namespace std;
double dx2(int t, int x, int dx)
{
return (-9.8*cos(x));
}
int square(int x)
{
return (x*x);
}
double RK4(float t, float x, float dx, float h)
{
double k1, k2, k3, k4, l1, l2, l3, l4, diff1, diff2;
k1 = h*dx2(t,x,dx);
l1 = h*k1;
k2 = h*dx2(t+h/2,x+l1/2,dx+k1/2);
l2 = h*k2;
k3 = h*dx2(t+h/2,x+l2/2,dx+k2/2);
l3 = h*k3;
k4 = h*dx2(t+h,x+l3,dx+k3);
l4 = h*k4;
diff1 = (l1+2*l2+2*l3+l4)/float(6);
diff2 = (k1+2*k2+2*k3+k4)/float(6);
double OUT[] = {diff1, diff2};
return OUT;
}
int main()
{
double diff, t, t0, t1, x, x0, dx, dx0, h, N;
N = 1000;
t0 = 0;
t = t0;
t1 = 10;
x0 = 0;
x = x0;
dx0 = 0;
dx = dx0;
h = (t1 - t0) / float(N);
for(int i = 1; i<=N; i++) {
diff = RK4(t,x,dx,h);
x = x + diff;
t = t + h;
}
cout << diff;
return 0;
}正如您在这个程序中所看到的,我正在求解二阶微分方程(如果有方法将LaTeX方程插入到我的问题中,请告诉我):
d2x/dt2= -9.8 cos(x)
这是单摆运动方程的一个例子。问题线分别是33和34。在它中,我试图将OUT数组的第一个元素定义为diff1,第二个元素定义为diff2。每当我编译这个程序(名为example.cpp)时,我都会得到错误:
g++ -Wall -o "example" "example.cpp" (in directory: /home/fusion809/Documents/CodeLite/firstExample)
example.cpp: In function ‘double RK4(float, float, float, float)’:
example.cpp:33:9: error: cannot convert ‘double*’ to ‘double’ in return
return OUT;
^~~
Compilation failed.发布于 2016-07-11 04:21:27
确切地说,因为您返回的是double的数组,这会退化为double*,但是函数被定义为返回double。在C++中,类型T和T类型的数组是不同的类型,一般情况下,它们不能相互转换。
在这种情况下,使用std::pair<T1, T2> (#include <utility>)可能更好,因为您使用的是C++和标准库,或者是具有两个类型double字段的结构。查找std::pair<>和std::tie<>,前者用于生成不同类型的元素对,后者用于生成不同类型的任意大小的元组。
当您将std::pair的元素写入std::cout时,请使用first、second成员来访问这对字段。不能使用重载的std::cout流运算符直接输出std::pair。
编辑:
#include <utility>
std::pair<double, double> RK4(float t, float x, float dx, float h)
{
/* snip */
diff1 = (l1+2*l2+2*l3+l4)/float(6);
diff2 = (k1+2*k2+2*k3+k4)/float(6);
return {diff1, diff2};
}
int main()
{
double x, dx;
/* snip */
for(int i = 1; i<=N; i++) {
std::pair<double, double> diff = RK4(t,x,dx,h);
// or use with C++11 and above for brevity
auto diff = RK4(t,x,dx,h);
x = x + diff.first;
dx = dx + diff.second;
t = t + h;
}
cout << x << " " << dx << "\n" ;
return 0;
}发布于 2016-07-11 04:23:56
RK4函数的返回类型是double,它是一个值,但是您试图返回其中两个值的数组。那不管用。您可以将返回类型更改为double*,并使用new double[2]分配数组,但是使用std::pair<double, double>作为返回类型会更简单、更安全。然后你就可以做return { diff1, diff2 };了。
发布于 2016-07-11 10:30:20
要从函数返回几个值,您可以选择如下:
std::vector
向量RK4(浮动t,浮点数x,浮点数x,浮点数h) { // .返回{{diff1,diff2}};}std::tuple或std::pair (限制为2个元素):
std::pair RK4(浮t,浮x,浮dx,浮h) { // .返回{{diff1,diff2}};}
或
std::tuple RK4(浮t,浮x,浮dx,浮h) { // .返回{{diff1,diff2}};}https://stackoverflow.com/questions/38299083
复制相似问题