c - 使用欧拉方法和指针算术的模型不起作用

标签 c pointers model while-loop

我是 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/

相关文章:

c++ - C、C++中的中断机制

c++ - 如何在 C++ 中从 "pointer-to-objects"的 vector 访问对象

c - 函数给出期望的输出然后异常终止

ruby-on-rails - ruby on Rails 中的 after_update 回调

mysql - 路径枚举 mySQL 查询以创建面包屑

c - C 中通过函数调用和参数使用指针时的语法错误

将参数复制到函数指针

c - 为多条消息重用一个管道

c++ - 如何声明指向 C++11 std::array 的指针?

ruby-on-rails - validates_presence_of + :message shows the name of the field