语境
我想模拟电场中粒子的轨迹。我想要它在每个时间步的位置、速度和加速度。这些变量中的每一个都将存储在一个数组中,因此我可以将其写入文件并稍后绘制。我的问题是我无法修改数组的值,当我打印时,我只会得到在整个数组中重复的初始值。
我的代码
int main(){
////// Some variable definitions for the physics //////
const float m_Ca = 40*1.66053886e-27;
const float Q_Ca = 1.60217646e-19;
const float U_dc = 1000;
const float z0_2 = 20*20; // mm
const float w_z_2 = 2*Q_Ca*U_dc/m_Ca/z0_2;
// time step
const float dt = 5e-9;
const float dt1 = 0.5*5e-9;
// simulation number of steps
const int i_free_fly = round(10/sqrtf(w_z_2)/dt);
///////////////////////////////////////////////////////
// allocating position, velocity and acceleration arrays
float* r_z = (float*)malloc(i_free_fly*sizeof(float));
float* v_z = (float*)malloc(i_free_fly*sizeof(float));
float* a_z = (float*)malloc(i_free_fly*sizeof(float));
// initializing arrays
r_z[0] = 1;
v_z[0] = 0;
a_z[0] = 0;
// Velocity-Verlet algorithm
// here I calculate the next steps position, velocity and acceleration
// for the current time step i I need info from the previous time step i-1
for (int i=1;i<i_free_fly;++i){
// update position
r_z[i] = r_z[i-1] + v_z[i-1]*dt + 0.5*a_z[i-1]*dt1*dt1;
// update acceleration
a_z[i] = m_Ca*w_z_2*r_z[i];
// update velocity
v_z[i] = v_z[i-1] + dt1 * (a_z[i-1] + a_z[i]);
}
return 0;
}
我的问题
打印 r_z、v_z 和 a_z 时,我随时都会得到 1、0、0 和零。我这样做是为了打印数组。
for (int i=1;i<150;++i){
printf("%f\n",r_z[i]);
printf("%f\n",v_z[i]);
printf("%f\n",a_z[i]);
}
我是 C 新手,指针对我来说仍然很奇怪。我不知道使用它们是否是正确的方法,但是在互联网上查看我认为这是实现我的目的的最佳方法,但我可能错过了一些东西。