我是 C 语言新手,并且不太熟悉编写任何超过几行的程序。
我正在尝试为受重力和阻力作用的自由落体物体编写一个模型。它使用欧拉方法求解两个一阶微分方程,一个用于位置,一个用于速度。
所以我们有:F = m dv/dt = -mg - k|v|v 和 dy/dt = v
这些问题的求解方法为:Vn+1 = Vn - (delta t*(g+(k/m)|Vn|Vn)) 和 Yn+1 = Yn + (delta t * Vn)
(在此 Vn+1 是第 n+1 项等)
在我的程序中,我尝试使用两个函数,分别用于位置和速度,它们通过在它们和主函数之间传递带有 Y 和 V 值的指针来工作,然后它应该循环直到 Y=0 并打印出每一步的值。
当我运行它时,它会显示如下内容:http://imgur.com/DNHIhHI
谁能告诉我这有什么问题,或者我是否需要完全使用不同的方法?
非常感谢,代码如下
#include <stdio.h>
void Velocity(double *ptr, double m, double k, double t);
void Position(double *pst, double *ptr, double t );
int main()
{
double k = 18833.5608;
double t = 0;
double m;
double speed = 0;
double *ptr = &speed;
double y = 1000;
double *pst = &y;
printf("Enter mass of object: \n");
scanf("%f" , &m);
do
{
Velocity( ptr, m, k, t );
printf("Velocity at time %f is: %f\n" , t, speed);
Position( pst, ptr, t);
printf("Position at time %f is: %f\n" , t , y);
t++;
}
while((y>0));
return 0;
}
void Velocity(double *velo, double m, double k, double t)
{
double g = 9.80665;
*velo = *velo - (t*(g+((k/m)*fabs(*velo)**(velo))));
}
void Position(double *Y , double *velo, double t )
{
*Y = *Y+(t*(*velo));
}
最佳答案
在编写进行计算的程序时(使用任何语言,而不仅仅是 C),请尝试使执行计算的代码接受参数并返回结果,但不这样做改变变量。也就是说,不要写:
void do_calculation( double * result, double x, double y)
{
*result = x + y;
}
...
double r;
do_calculation(&r, 123, 456);
改为写
double do_calculation(double x, double y)
{
return x + y;
}
...
double r = do_calculation(123, 456);
有道理吗?
如果您想修改现有值,请再次强调,不要将其作为要改变的变量传递。而不是
void do_calculation(double * accumulator, double x, double y)
{
*accumulator = *accumulator + x + y;
}
...
double r = 10;
do_calculation(&r, 123, 456);
而是说
double do_calculation(double original, double x, double y)
{
return original + x + y;
}
...
double r = 10;
r = do_calculation(r, 123, 456);
现在,一旦您的程序架构更加合理,您就需要学习如何调试小程序。可以在这里找到有关该主题的一些好建议:
http://ericlippert.com/2014/03/05/how-to-debug-small-programs/
关于c - 使用欧拉方法和指针算术的模型不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22694228/