gpt4 book ai didi

c++ - 如何创建具有可变元素的 C++ 数组?

转载 作者:行者123 更新时间:2023-11-30 01:10:17 28 4
gpt4 key购买 nike

我有这个 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 余弦(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.

最佳答案

没错,因为您要返回一个 double 的数组的,衰减到 double* , 但该函数被定义为返回 double . T 类型的数组和类型 T在C++中是不同的类型,一般来说它们之间不能相互转换。

在这种情况下,您最好使用 std::pair<T1, T2> ( #include <utility> ) 因为您使用的是 C++ 和标准库,或者具有两个 double 类型字段的结构.查找std::pair<>std::tie<> ,前者用于制作不同类型的元素对,后者用于制作任意大小的不同类型的元组。

当你写 std::pair的元素到 std::cout , 使用 first , second成员访问该对的字段。 std::pair std::cout 无法使用重载流运算符直接输出.

编辑:

#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;
}

关于c++ - 如何创建具有可变元素的 C++ 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38299083/

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